home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 10 / AACD 10.iso / AACD / Online / SpeakFreely / src / speaker.c < prev    next >
C/C++ Source or Header  |  2000-05-18  |  78KB  |  2,614 lines

  1. /*
  2.  
  3.             Speak Freely for Unix
  4.              Sound Output Server
  5.  
  6.     Designed and implemented in July of 1991 by John Walker.
  7.  
  8. */
  9.  
  10. #include "speakfree.h"
  11. #include "version.h"
  12. static int audiok = FALSE;          /* Audio initialised flag */
  13. static int audiotime = 0;          /* Audio timeout counter */
  14. static int debugging = FALSE;          /* Debugging enabled */
  15. static int debugforce = FALSE;          /* Debugging forced / prevented ? */
  16. #ifdef HEXDUMP
  17. static int hexdump = FALSE;          /* Dump received packets in hex ? */
  18. #endif
  19. static int noring = FALSE;          /* Disable remote ring requests */
  20. gsm gsmh;                  /* GSM handle */
  21. static char deskey[9] = "";           /* DES key, if any */
  22. static char rtpdeskey[9] = "";        /* RTP DES key, if any */
  23. static char vatdeskey[9] = "";        /* VAT DES key, if any */
  24. static char ideakey[17] = "";         /* IDEA key, if any */
  25. static char blowfish_spec = FALSE;    /* Nonzero if Blowfish key specified */
  26. #ifdef CRYPTO
  27. static BF_KEY blowfishkey;          /* Blowfish key */
  28. #endif
  29. static char *curotp = NULL;          /* Key file, if any */
  30. static int whichport = Internet_Port; /* Port to listen on (base address) */
  31. static int sock;              /* Data socket */
  32. static int ssock;              /* Control socket (RTP/VAT) */
  33. static struct sockaddr_in from;       /* Sending host address */
  34. static struct sockaddr_in name;       /* Address of destination host */
  35. static int fromlen;              /* Length of sending host address */
  36. static int rll;               /* Length of packet read from socket */
  37. static int showhosts = FALSE;          /* Show host names that connect */
  38. static int hosttimeout = 180 * 1000000L; /* Consider host idle after this time */
  39. static int jitter = 0;              /* Jitter compensation delay */
  40. static int jitterwait = 0;          /* Jitter wait in progress */
  41. static int jitteridle = 0;          /* Countdown to reset jitter timer */
  42. static int jitteridlet = 0;          /* Jitter idle timeout interval */
  43. struct jitterbuf {              /* Jitter queue item */
  44.     struct jitterbuf *next;
  45.     LONG length;
  46.     char value[2];
  47. };
  48. static struct jitterbuf *jithead = NULL, *jittail = NULL; /* Jitter queue links */
  49. static char *prog;              /* Program name */
  50. static FILE *record = NULL;          /* Answering machine record file */
  51. static char *pgppass = NULL;          /* PGP secret key password */
  52. static char *replyfile = NULL;          /* Reply file pathname */
  53. static char *replycmdexe = NULL;
  54. static char *replycmd = "sfmike -t";  /* Default reply command */
  55. static char *busysignal = "sleep 10; sfmike %s busy.au"; /* Default busy signal command */
  56. static int busytimeout = 60 * 1000000L; /* Busy signal timeout interval */
  57. static int dobusy = FALSE;          /* Reject calls when busy ? */
  58. #ifdef HALF_DUPLEX
  59. static struct in_addr localhost;      /* Our internet address */
  60. static int halfDuplexMuted = FALSE;   /* Muted by half-duplex transmission */
  61. #endif
  62.  
  63. static struct sockaddr_in lookhost;   /* Look who's listening host, if any */
  64. static char *sdes = NULL;          /* RTP SDES packet */
  65. static int sdesl;              /* RTP SDES packet length */
  66. static unsigned long ssrc;          /* RTP synchronisation source identifier */
  67. static int lwltimer;              /* Seconds before next LWL retransmit */
  68. static int lwlonly = FALSE;          /* LWL broadcast only ? */
  69. static int actives = 0;           /* Currently active hosts */
  70. static int faceTransferActive = 0;    /* Face transfers in progress */
  71.  
  72. #define LWL_RETRANSMIT    (5 * 60 * 1000000L) /* Microseconds between LWL updates */
  73. #define LWL_STRIKEOUT    5          /* Abandon LWL transmission to site
  74.                      after this number of consecutive
  75.                      failures. */
  76.  
  77. static struct in_addr lwl_sites[LWL_MAX_SITES]; /* LWL site addresses */
  78. static long lwl_ports[LWL_MAX_SITES]; /* Ports for LWL hosts */
  79. static int lwl_strikes[LWL_MAX_SITES];/* Consecutive failures to send LWL packet */
  80. static int lwl_nsites = 0;          /* Number of LWL sites published on */
  81.  
  82. static FILE *facefile = NULL;         /* User's face image */
  83. static int facesDisplayed = 0;          /* Face viewers currently active */
  84.  
  85. static struct connection *conn = NULL;/* Chain of current connections */
  86.  
  87. /* Audio output and control device file names. */
  88.  
  89. #ifdef AUDIO_DEVICE_FILE
  90. extern char *devAudioOutput, *devAudioControl;
  91. #endif
  92.  
  93. #define Debug    ((debugforce != 0) ? (debugforce > 0) : debugging)
  94.  
  95. #define TickTock    (10 * 1000000L)   /* Alarm interval in microseconds */
  96. #define TockTock    (60 * 1000000L)   /* Alarm interval when no connections open */
  97. #define JitterTock  (1000000L / 4)    /* Alarm interval for jitter compensation */
  98.  
  99. #ifdef AUDIO_RELEASE
  100. #define AudioRelease (AUDIO_RELEASE * 1000000L) /* Release audio when idle this long */
  101. #else
  102. #define AudioRelease (20 * 1000000L)  /* Release audio when idle this long */
  103. #endif
  104.  
  105. static int timerStep = TockTock;      /* Current timer step */
  106.  
  107. #define ucase(x)    (islower(x) ? toupper(x) : (x))
  108.  
  109. /*  GSMDECOMP  --  Uncompress the contents of a sound buffer using GSM.  */
  110.  
  111. static void gsmdecomp(sb)
  112.   struct soundbuf *sb;
  113. {
  114.     gsm_signal dst[160];
  115.     int i, j, l = 0;
  116.     char *dpx = ((char *) sb->buffer.buffer_val) + sizeof(short);
  117.     static char dcb[BUFL];
  118.     short declen = ntohs(*((short *) sb->buffer.buffer_val));
  119.  
  120.     /* Since some old releases forget to convert this field
  121.        from network byte order, kludge it back to sanity
  122.        if this happens.  First we try swapping the bytes.  If
  123.        that doesn't work, force the standard buffer length.
  124.        Note that we have to write this out, as ntohs will be
  125.        a no-op on a big-endian machine. */
  126.  
  127.     if (declen <= 0 || declen > 1600) {
  128.     declen = ((declen & 0xFF) << 8) | ((declen >> 8) & 0xFF);
  129.     }
  130.     if (declen <= 0 || declen > 1600) {
  131.     declen = 1600;
  132.     }
  133.     for (i = 0; i < sb->buffer.buffer_len - sizeof(short);
  134.         i += sizeof(gsm_frame)) {
  135.     gsm_decode(gsmh, (gsm_byte *) dpx, dst);
  136.     dpx += sizeof(gsm_frame);
  137.     for (j = 0; j < 160; j++) {
  138.         dcb[l++] = audio_s2u(dst[j]);
  139.     }
  140.     }
  141.     bcopy(dcb, sb->buffer.buffer_val, declen);
  142.     sb->buffer.buffer_len = declen;
  143. }
  144.  
  145. /*  LPCDECOMP  --  Uncompress the contents of a sound buffer using LPC.  */
  146.  
  147. static void lpcdecomp(sb, c)
  148.   struct soundbuf *sb;
  149.   struct connection *c;
  150. {
  151.     int i, l = 0;
  152.     char *dpx = ((char *) sb->buffer.buffer_val) + sizeof(short);
  153.     char dcb[BUFL];
  154.     short declen = ntohs(*((short *) sb->buffer.buffer_val));
  155.  
  156.     if (declen <= 0 || declen > (10 * LPC_FRAME_SIZE)) {
  157.     declen = 10 * LPC_FRAME_SIZE;
  158.     }
  159.     for (i = 0; l < declen;
  160.         i += LPCRECSIZE) {
  161.     lpc_synthesize(dcb + l, (lpcparams_t *) (dpx + i), &c->lpcc);
  162.     l += LPC_FRAME_SIZE;
  163.     }
  164.     bcopy(dcb, sb->buffer.buffer_val, declen);
  165.     sb->buffer.buffer_len = declen;
  166. }
  167.  
  168. /*  LPC10DECOMP  --  Uncompress the contents of a sound buffer using LPC10.  */
  169.  
  170. static void lpc10decomp(sb, c)
  171.   struct soundbuf *sb;
  172.   struct connection *c;
  173. {
  174.     int j;
  175.     char *dpx = ((char *) sb->buffer.buffer_val);
  176.     char dcb[BUFL];
  177.  
  178.     j = lpc10decode(dpx, dcb, sb->buffer.buffer_len);
  179.     bcopy(dcb, sb->buffer.buffer_val, j);
  180.     sb->buffer.buffer_len = j;
  181. }
  182.  
  183. /*  ETIME  --  Edit time and date for log messages.  */
  184.  
  185. static char *etime()
  186. {
  187.     struct tm *t;
  188.     time_t clock;
  189.     static char s[20];
  190.  
  191.     time(&clock);
  192.     t = localtime(&clock);
  193.     sprintf(s, "%02d-%02d %02d:%02d", t->tm_mon + 1, t->tm_mday,
  194.            t->tm_hour, t->tm_min);
  195.     return s;
  196. }
  197.  
  198. /*  COMPRESSIONTYPE  --  Return a string describing the type of
  199.              compression employed in this buffer.  Assumes
  200.              this *is*, in fact, a sound buffer and not
  201.              an RTP packet, face data, etc.  */
  202.  
  203. static char *compressionType(msg)
  204.   soundbuf *msg;
  205. {
  206.     return ((msg->compression & (fComp2X | fCompGSM)) ==
  207.                 (fComp2X | fCompGSM)) ?
  208.                                 "GSM+2X compressed" :
  209.        ((msg->compression & (fComp2X | fCompADPCM)) ==
  210.                 (fComp2X | fCompADPCM)) ?
  211.                                 "ADPCM+2X compressed" :
  212.        ((msg->compression & (fComp2X | fCompLPC)) ==
  213.                 (fComp2X | fCompLPC)) ?
  214.                                 "LPC+2X compressed" :
  215.        ((msg->compression & (fComp2X | fCompLPC10)) ==
  216.                 (fComp2X | fCompLPC10)) ?
  217.                                 "LPC10+2X compressed" :
  218.        ((msg->compression & (fComp2X | fCompVOX)) ==
  219.                 (fComp2X | fCompVOX)) ?
  220.                                 "VOX+2X compressed" :
  221.            ((msg->compression & fCompADPCM) ? "ADPCM compressed" :
  222.            ((msg->compression & fCompLPC) ? "LPC compressed" :
  223.            ((msg->compression & fCompLPC10) ? "LPC10 compressed" :
  224.            ((msg->compression & fComp2X) ? "2X compressed" :
  225.            ((msg->compression & fCompGSM) ? "GSM compressed" :
  226.            ((msg->compression & fCompVOX) ? "VOX compressed" :
  227.                                             "uncompressed"))))));
  228. }
  229.  
  230. /*  MAKESESSIONKEY  --    Generate session key.  */
  231.  
  232. static void makeSessionKey(key)
  233.   char *key;
  234. {
  235.     int j;
  236.     struct MD5Context md5c;
  237.     char md5key[16], md5key1[16];
  238.     char s[1024];
  239.  
  240.     s[0] = 0;
  241.     sprintf(s + strlen(s), "%u", getpid());
  242.     sprintf(s + strlen(s), "%u", getppid());
  243.     V getcwd(s + strlen(s), 256);
  244.     sprintf(s + strlen(s), "%u", clock());
  245.     V cuserid(s + strlen(s));
  246.     sprintf(s + strlen(s), "%u", time(NULL));
  247. #ifdef Solaris
  248.     sysinfo(SI_HW_SERIAL, s + strlen(s), 12);
  249. #else
  250.     sprintf(s + strlen(s), "%u", gethostid());
  251. #endif
  252.     getdomainname(s + strlen(s), 256);
  253.     gethostname(s + strlen(s), 256);
  254.     sprintf(s + strlen(s), "%u", getuid());
  255.     sprintf(s + strlen(s), "%u", getgid());
  256.     MD5Init(&md5c);
  257.     MD5Update(&md5c, s, strlen(s));
  258.     MD5Final(md5key, &md5c);
  259.     sprintf(s + strlen(s), "%u", (time(NULL) + 65121) ^ 0x375F);
  260.     MD5Init(&md5c);
  261.     MD5Update(&md5c, s, strlen(s));
  262.     MD5Final(md5key1, &md5c);
  263. #ifdef CRYPTO
  264.     init_idearand(md5key, md5key1, time(NULL));
  265. #endif
  266.     for (j = 0; j < 16; j++) {
  267. #ifdef CRYPTO
  268.     key[j] = idearand();
  269. #else
  270.     key[j] = md5key[j] ^ md5key1[j];
  271. #endif
  272.     }
  273. #ifdef CRYPTO
  274.     close_idearand();
  275. #endif
  276. }
  277.  
  278. /*  ULARM  --  Wrapper for setitimer() that looks like alarm()
  279.            but accepts a time in microseconds.  */
  280.  
  281. static void ularm(t)
  282.   long t;
  283. {
  284.     struct itimerval it;
  285.  
  286.     it.it_value.tv_sec = t / 1000000L;
  287.     it.it_value.tv_usec = t % 1000000L;
  288.     it.it_interval.tv_sec = it.it_interval.tv_usec = 0;
  289.     setitimer(ITIMER_REAL, &it, NULL);
  290. }
  291.  
  292. /*  WINDTIMER  --  Reset alarm timer to appropriate value
  293.                    depending on what's going on at the moment.  */
  294.  
  295. static void windtimer()
  296. {
  297.     if (faceTransferActive > 0) {
  298.     /* There is an implicit assumption here that FaceFetchInterval
  299.        is <= JitterTock.  If this is not the case, jitter compensation
  300.        may be too coarse during a face transfer. */
  301.     timerStep = FaceFetchInterval;
  302.     } else if (audiok || (actives > 0)) {
  303.     timerStep = (jitteridle > 0) ? JitterTock : TickTock;
  304.     } else {
  305.     timerStep = TockTock;
  306.     }
  307.     ularm(timerStep);
  308. }
  309.  
  310. /*  ISBUSY  --    Test if a connection is active (item on connection
  311.         chain with a protocol other than PROTOCOL_UNKNOWN).  */
  312.  
  313. static int isBusy()
  314. {
  315.     struct connection *c;
  316.  
  317.     c = conn;
  318.     while (c != NULL) {
  319.     if (c->con_protocol != PROTOCOL_UNKNOWN) {
  320.         return dobusy;
  321.     }
  322.     c = c->con_next;
  323.     }
  324.     return FALSE;
  325. }
  326.  
  327. /*  SENDLWLMESSAGE  --    If enabled, send a message identifying us
  328.                         to each selected Look Who's Listening server.  */
  329.  
  330. static void sendLwlMessage(dobye)
  331.   int dobye;
  332. {
  333.     int i, sock;
  334.  
  335.     for (i = 0; i < lwl_nsites; i++) {
  336.     if (lwl_ports[i] >= 0) {
  337.         if (Debug) {
  338.                 fprintf(stderr, "%s: updating LWL data at %s\n",
  339.             prog, inet_ntoa(lwl_sites[i]));
  340.         }
  341.         sock = socket(AF_INET, SOCK_STREAM, 0);
  342.         if (sock < 0) {
  343.                 perror("opening look who's listening socket");
  344.         sdes = NULL;
  345.         return;
  346.         }
  347.  
  348.         lookhost.sin_port = htons(lwl_ports[i]);
  349.         bcopy((char *) (&lwl_sites[i]), (char *) &lookhost.sin_addr.s_addr,
  350.           sizeof lookhost.sin_addr.s_addr);
  351.  
  352.         if (connect(sock, (struct sockaddr *) &(lookhost), sizeof lookhost) >= 0) {
  353.         if (dobye) {
  354.             char v[1024];
  355.             int l;
  356.  
  357.                     l = rtp_make_bye(v, ssrc, "Exiting sfspeaker", FALSE);
  358.             if (send(sock, v, l, 0) < 0) {
  359.                         perror("sending look who's listening BYE packet");
  360.             }
  361.                     /* No point in clearing strikes if we're exiting. */
  362.         } else {
  363.             if (send(sock, (char *) sdes, sdesl, 0) < 0) {
  364.                         perror("sending look who's listening source ID message");
  365.             } else {
  366.             lwl_strikes[i] = 0; /* Success--clear strikes */
  367.             }
  368.         }
  369.         } else {
  370.                 perror("connecting look who's listening socket");
  371.  
  372.         /* If we get a connection refused reply, increment the number
  373.            of strikes against the server.  If the server strikes out,
  374.            remove it from the list of server to which we send our
  375.            LWL information. */
  376.  
  377.         if (errno == ECONNREFUSED) {
  378.             if ((++lwl_strikes[i]) >= LWL_STRIKEOUT) {
  379.             if (Debug) {
  380.                             fprintf(stderr, "%s: abandoning LWL transmission to %s\n",
  381.                 prog, inet_ntoa(lwl_sites[i]));
  382.             }
  383.             lwl_ports[i] = -1;
  384.             }
  385.         }
  386.         }
  387.     }
  388.     }
  389.     lwltimer = LWL_RETRANSMIT;
  390.     close(sock);
  391. }
  392.  
  393. /*  OBTAINAUDIO  --  Attempt to obtain the audio output device.  */
  394.  
  395. static void obtainaudio()
  396. {
  397.     if (!audiok) {
  398.     if (!soundinit(O_WRONLY)) {
  399.             perror("opening audio output device");
  400.             fprintf(stderr, "A common cause of this error is a sound board or\n");
  401.             fprintf(stderr, "driver which cannot run in full duplex mode (some\n");
  402.             fprintf(stderr, "boards which are physically capable of full duplex\n");
  403.             fprintf(stderr, "have drivers which cannot run them in this mode).\n\n");
  404.             fprintf(stderr, "Try uncommenting the line:\n\n");
  405.             fprintf(stderr, "    DUPLEX = -DHALF_DUPLEX\n\n");
  406.             fprintf(stderr, "in the Makefile, then \"make clean\", then \"make\".\n");
  407.             fprintf(stderr, "This will operate your board in half-duplex mode\n");
  408.             fprintf(stderr, "and avoid the conflict which probably caused the\n");
  409.             fprintf(stderr, "error opening audio output.\n");
  410.             return;                   /* Can't acquire sound device */
  411.     }
  412.     audiok = TRUE;
  413.     if (Debug) {
  414.             fprintf(stderr, "%s: opening audio device.\n", prog);
  415.     }
  416.     windtimer();              /* Reset timer, if necessary */
  417.     }
  418. }
  419.  
  420. /*  FLUSHJITTER  --  Flush any buffers waiting in the jitter compensation
  421.              queue.  */
  422.  
  423. static void flushjitter()
  424. {
  425.     struct jitterbuf *jb;
  426.  
  427.     /* If any samples are pending in the jitter queue, flush
  428.        them to the audio output.  */
  429.  
  430.     if ((jb = jithead) != NULL) {
  431.     jithead = jittail = NULL;
  432.  
  433.     if (Debug) {
  434.             fprintf(stderr, "Flushing jitter queue.\n");
  435.     }
  436.     obtainaudio();
  437.     while (jb != NULL) {
  438.         struct jitterbuf *jo = jb;
  439.  
  440.         if (Debug) {
  441.         fprintf(stderr,
  442.                         "Playing %d samples from jitter queue.\n", jb->length);
  443.         }
  444.         if (audiok) {
  445.         audiotime = 0;
  446.         soundplay(jb->length, jb->value);
  447.         }
  448.         jb = jb->next;
  449.         free(jo);
  450.     }
  451.     }
  452. }
  453.  
  454. /*  RELEASE  --  Signal-catching function which releases the audio
  455.                  device if we haven't received anything to play in
  456.          the last minute. */
  457.  
  458. static void release()
  459. {
  460.     struct connection *c, *l, *n;
  461.  
  462.     /* Mark idle any hosts that haven't sent us anything recently. */
  463.  
  464.     c = conn;
  465.     l = NULL;
  466.     actives = 0;
  467.     while (c != NULL) {
  468.     if ((c->con_timeout >= 0) && (c->con_timeout < hosttimeout)) {
  469.         c->con_timeout += timerStep;
  470.         actives++;
  471.     }
  472.  
  473.     /* If the busy signal timer is running, decrement it.
  474.        Once it expires the host becomes eligible to attempt
  475.        to connect once again.  In essence, the connection
  476.        is held open until the busy signal timeout expires, and
  477.        is then forced to go idle with the regular timeout
  478.        mechanism, making it eligible once again to attempt
  479.        connection. */
  480.  
  481.     if (c->con_busy > 0) {
  482.         c->con_busy -= timerStep;
  483.         if (c->con_busy <= 0) {
  484.         c->con_busy = 0;
  485.         c->con_timeout = hosttimeout;
  486.         if (Debug) {
  487.                     fprintf(stderr, "%s: %s %s busy signal timeout expired\n", prog, etime(), c->con_hostname);
  488.         }
  489.         }
  490.     }
  491.     n = c->con_next;
  492.     if (c->con_timeout >= hosttimeout) {
  493.         actives--;              /* Oops--just went inactive */
  494.         c->con_timeout = -1;      /* Mark inactive */
  495.         if (showhosts) {
  496.                 fprintf(stderr, "%s: %s %s idle\n", prog, etime(), c->con_hostname);
  497.         }
  498.         c->con_protocol = PROTOCOL_UNKNOWN;
  499.         c->con_uname[0] = c->con_email[0] = 0;
  500.         c->con_rseq = -1;
  501.  
  502.         /* If a face file transfer is in progress, shut it down and
  503.            discard the incomplete face file. */
  504.  
  505.         if (c->face_stat == FSrequest || c->face_stat == FSreply) {
  506.         if (c->face_file != NULL) {
  507.             fclose(c->face_file);
  508.             c->face_file = NULL;
  509.         }
  510.         unlink(c->face_filename);
  511.         c->face_filename[0] = 0;
  512.         faceTransferActive--;
  513.         }
  514.  
  515.             /* If there's a face viewer active, terminate it and delete
  516.            the face image file, if any. */
  517.  
  518.         if (c->face_viewer > 0) {
  519.         kill(c->face_viewer, SIGHUP);
  520.         c->face_viewer = 0;
  521.         if (facesDisplayed > 0) {
  522.             facesDisplayed--;
  523.         }
  524.         unlink(c->face_filename);
  525.         c->face_filename[0] = 0;
  526.         c->face_file = NULL;
  527.         }
  528.         c->face_stat = FSinit;
  529.  
  530.             /* If there's a PGP session key for this host, don't actually
  531.            release the connection buffer, as that would lose it.  Issue
  532.            an idle message, though, and tweak the timeout so we do this
  533.            only once. */
  534.  
  535.         if (c->pgpkey[0] == 0) {
  536.         if (l == NULL) {
  537.             conn = n;
  538.         } else {
  539.             l->con_next = n;
  540.         }
  541.         free(c);
  542.         }
  543.     } else {
  544.         int makereq = FALSE;
  545.  
  546.         /* If a face file transfer is in progress, request
  547.                the next block or, if it's time, re-issue the last
  548.            request if the timeout has expired. */
  549.  
  550.         if (c->face_stat == FSreply) {
  551.         makereq = TRUE;
  552.         c->face_retry = 0;
  553.         if (Debug) {
  554.                     fprintf(stderr, "%s: request face data at %ld from %s\n",
  555.             prog, c->face_address, c->con_hostname);
  556.         }
  557.         } else if (c->face_stat == FSrequest) {
  558.         c->face_timeout += timerStep;
  559.         if (c->face_timeout >= FaceTimeout) {
  560.             if (Debug) {
  561.                         fprintf(stderr, "%s: retry %d reissue face data request at %ld from %s\n",
  562.                 prog, c->face_retry, c->face_address, c->con_hostname);
  563.             }
  564.             if (c->face_retry > FaceMaxRetries) {
  565.             if (c->face_file != NULL) {
  566.                 fclose(c->face_file);
  567.                 c->face_file = NULL;
  568.             }
  569.             unlink(c->face_filename);
  570.             c->face_filename[0] = 0;
  571.             c->face_stat = FSabandoned;
  572.             faceTransferActive--;
  573.             if (Debug) {
  574.                             fprintf(stderr, "%s: timeout, no face image available for %s\n",
  575.                 prog, c->con_hostname);
  576.             }
  577.             } else {
  578.             makereq = TRUE;
  579.             c->face_retry++;
  580.             }
  581.         }
  582.         }
  583.  
  584.         if (makereq) {
  585.         sbhead fsb;
  586.  
  587.         c->face_stat = FSrequest;
  588.         c->face_timeout = 0;
  589.         bcopy((char *) &(c->con_addr), (char *) &(name.sin_addr),
  590.             sizeof(struct in_addr));
  591.         fsb.compression = htonl(fProtocol | fFaceData | faceRequest);
  592.         fsb.buffer.buffer_len = htonl(c->face_address);
  593.         if (sendto(sock, (char *) &fsb,
  594.             (int) (sizeof(struct soundbuf) - BUFL),
  595.             0, (struct sockaddr *) &(name), sizeof name) < 0) {
  596.                     perror("requesting face image data");
  597.         }
  598.         }
  599.  
  600.         l = c;
  601.     }
  602.     c = n;
  603.     }
  604.  
  605.     /* Release the sound device after two ticks.  This allows
  606.        other programs to use it while we're idle. */
  607.  
  608.     if (audiok && ((audiotime += timerStep) >= AudioRelease)) {
  609.     soundterm();
  610.     audiok = FALSE;
  611.     if (Debug) {
  612.             fprintf(stderr, "%s: releasing audio device.\n", prog);
  613.     }
  614.  
  615.         /* Flush the record file so if we're rudely terminated it
  616.        will be up to date as of the last audio idle time. */
  617.  
  618.     if (record != NULL) {
  619.         fflush(record);
  620.     }
  621.     }
  622.  
  623.     /* Update our Look Who's Listening information if the
  624.        timeout has expired. */
  625.  
  626.     lwltimer -= timerStep;
  627.     if (sdes != NULL && lwltimer <= 0) {
  628.     sendLwlMessage(FALSE);
  629.     }
  630.  
  631.     /* If sound is waiting in the jitter queue, decrement the
  632.        jitter timer and flush the queue if it decrements to zero. */
  633.  
  634.     if (jithead != NULL && jitterwait > 0) {
  635.     jitterwait -= timerStep;
  636.     if (jitterwait <= 0) {
  637.         jitterwait = 0;
  638.         flushjitter();
  639.     }
  640.     }
  641.  
  642.     /* Count down the jitter idle timer.  When it's zero, the
  643.        first packets of an audio stream will be buffered in
  644.        the jitter queue. */
  645.  
  646.     if (jitteridle > 0) {
  647.     jitteridle -= timerStep;
  648.     if (jitteridle <= 0) {
  649.         jitteridle = 0;
  650.         if (Debug) {
  651.                 fprintf(stderr, "%s: jitter idle\n", prog);
  652.         }
  653.     }
  654.     }
  655.  
  656.     /* If we still own the sound device or have a connection
  657.        open, reset the timer. */
  658.  
  659.     windtimer();
  660.     if (Debug) {
  661.     time_t t = time(NULL);
  662.         fprintf(stderr, "%s: Tick: %.2f... %s", prog,
  663.         timerStep / 1000000.0, ctime(&t));
  664.     }
  665.     signal(SIGALRM, release);          /* Set signal to handle timeout */
  666. }
  667.  
  668. /*  EXITING  --  Catch as many program termination signals as
  669.          possible and clean up before exit.  */
  670.  
  671. static void exiting()
  672. {
  673.     struct connection *c = conn;
  674.  
  675.     if (sdes) {
  676.     sendLwlMessage(TRUE);
  677.     }
  678.  
  679.     /* Terminate any active face viewers. */
  680.  
  681.     while (c != NULL) {
  682.     if (c->face_viewer > 0) {
  683.         kill(c->face_viewer, SIGHUP);
  684.         unlink(c->face_filename);
  685.     }
  686.     c = c->con_next;
  687.     }
  688.  
  689.     exit(0);
  690. }
  691.  
  692. /*  VIEWERTERM    --  Handle termination of a face viewer child
  693.             process.  This is necessary both to avoid
  694.             viewers the user terminates manually becoming
  695.             zombie processes, and also to delete the
  696.             face file no longer associated with a viewer. */
  697.  
  698. static void viewerterm()
  699. {
  700.     int status, pid;
  701.  
  702.     while ((pid =
  703. #ifdef Solaris
  704.           /* Should work for any System V Unix. */
  705.           waitpid(0 /* or -1 */,&status, WNOHANG)
  706. #else
  707.           /* BSD and IRIX implement wait3(). */
  708.           wait3(&status, WNOHANG, 0)
  709. #endif
  710.        ) > 0) {
  711.     if (Debug) {
  712.             fprintf(stderr, "Child process %d done\n", pid);
  713.     }
  714.     if (WIFEXITED(status) || WIFSIGNALED(status)) {
  715.         struct connection *c = conn;
  716.  
  717.         while (c != NULL) {
  718.         if (pid == (int) c->face_viewer) {
  719.             c->face_viewer = 0;
  720.             unlink(c->face_filename);
  721.             if (Debug) {
  722.                         fprintf(stderr, "Face viewer pid %d terminated.  Deleting %s\n", pid, c->face_filename);
  723.             }
  724.             c->face_filename[0] = 0;
  725.             if (facesDisplayed > 0) {
  726.             facesDisplayed--;
  727.             if (facesDisplayed == 0) {
  728.             }
  729.             }
  730.         }
  731.         c = c->con_next;
  732.         }
  733.     }
  734.     }
  735.     signal(SIGCHLD, viewerterm);      /* Set signal to handle face viewer termination */
  736. }
  737.  
  738. /*  PLAYBUFFER    --  Send next buffer to audio output. */
  739.  
  740. static void playbuffer(msg, c)
  741.   soundbuf *msg;
  742.   struct connection *c;
  743. {
  744.     char *val;
  745.     LONG len;
  746.     char auxbuf[BUFL + 2], bbuf[8], tbuf[8];
  747.  
  748.     debugging = (msg->compression & fDebug) ? TRUE : FALSE;
  749.  
  750.     audiotime = 0;              /* Reset timeout counter */
  751.     obtainaudio();              /* Open audio output if necessary */
  752.  
  753.     if (showhosts && (c->con_compmodes != (fCompressionModes &
  754.         msg->compression))) {
  755.     c->con_compmodes = fCompressionModes & msg->compression;
  756.         fprintf(stderr, "%s: %s sending %s.\n", prog, c->con_hostname,
  757.         compressionType(msg));
  758.     }
  759.  
  760.     len = msg->buffer.buffer_len;
  761.     val = msg->buffer.buffer_val;
  762.  
  763.     if (Debug) {
  764.         fprintf(stderr, "%s: playing %d %s bytes from %s.\n", prog, len,
  765.         compressionType(msg), c->con_hostname);
  766.     }
  767.  
  768.     /* If the fSetDest bit is on, use the fDestJack bit to re-route
  769.        the sound.  This is normally used to divert the sound to the
  770.        speaker to get an individual's attention.  This can be
  771.        disabled with the -N option.  */
  772.  
  773.     if ((msg->compression & fSetDest) && !noring) {
  774.     sounddest((msg->compression & fDestJack) ? 1 : 0);
  775.     if (!(msg->compression & fDestJack)) {
  776.         if (audiok) {
  777.         soundplayvol(50);     /* Make sure volume high enough */
  778.         }
  779.     }
  780.     }
  781.  
  782. #ifdef CRYPTO
  783.  
  784.     /* If message is encrypted, decrypt. */
  785.  
  786.     if ((msg->compression & fEncOTP) && (curotp != NULL)) {
  787.     int i;
  788.     LONG slen = (len + 7) & (~7);
  789.  
  790.     if (Debug) {
  791.             fprintf(stderr, "%s: decrypting %d bytes with key file.\n", prog, len);
  792.     }
  793.     for (i = 0; i < slen; i ++) {
  794.         val[i] ^= curotp[i];
  795.     }
  796.     }
  797.  
  798.     if ((msg->compression & fEncPGP) && c->pgpkey[0]) {
  799.     unsigned short iv[4];
  800.     LONG slen = (len + 7) & (~7);
  801.  
  802.     bzero(iv, sizeof(iv));
  803.     initcfb_idea(iv, c->pgpkey + 1, TRUE);
  804.  
  805.     if (Debug) {
  806.             fprintf(stderr, "%s: decrypting %d bytes with PGP key.\n", prog, slen);
  807.     }
  808.     ideacfb(val, slen);
  809.     close_idea();
  810.     }
  811.  
  812.     if ((msg->compression & fEncBF) && blowfish_spec) {
  813.     unsigned char iv[8];
  814.     LONG slen = (len + 7) & (~7);
  815.  
  816.     bzero(iv, sizeof(iv));
  817.     if (Debug) {
  818.             fprintf(stderr, "%s: decrypting %d bytes with Blowfish key.\n", prog, slen);
  819.     }
  820.     BF_cbc_encrypt((unsigned char *) val, (unsigned char *) val,
  821.                slen, &blowfishkey, iv, BF_DECRYPT);
  822.     }
  823.  
  824.     if ((msg->compression & fEncIDEA) && ideakey[0]) {
  825.     unsigned short iv[4];
  826.     LONG slen = (len + 7) & (~7);
  827.  
  828.     bzero(iv, sizeof(iv));
  829.     initcfb_idea(iv, ideakey + 1, TRUE);
  830.  
  831.     if (Debug) {
  832.             fprintf(stderr, "%s: decrypting %d bytes with IDEA key.\n", prog, slen);
  833.     }
  834.     ideacfb(val, slen);
  835.     close_idea();
  836.     }
  837.  
  838.     if ((msg->compression & fEncDES) && deskey[0]) {
  839.     int i;
  840.     LONG slen = (len + 7) & (~7);
  841.  
  842.     setkey(deskey + 1);
  843.  
  844.     if (Debug) {
  845.             fprintf(stderr, "%s: decrypting %d bytes with DES key.\n", prog, slen);
  846.     }
  847.     for (i = 0; i < slen; i += 8) {
  848.         bcopy(val + i, tbuf, 8);
  849.         dedes(val + i);
  850.  
  851.         /* Reverse cipher block chaining. */
  852.  
  853.         if (i > 0) {
  854.         int j;
  855.  
  856.         for (j = 0; j < 8; j++) {
  857.             val[(i + j)] ^= bbuf[j];
  858.         }
  859.         }
  860.         bcopy(tbuf, bbuf, 8);
  861.     }
  862.     }
  863. #else
  864.     if ((msg->compression & (fEncDES | fEncOTP | fEncIDEA | fEncPGP | fEncBF)) &&
  865.     !(c->con_crypt_warning)) {
  866.     c->con_crypt_warning = TRUE;
  867.         fprintf(stderr, "%s: Warning: host %s is sending encrypted audio\n",
  868.         prog, c->con_hostname);
  869.         fprintf(stderr, "   which cannot be decoded by this version of\n");
  870.         fprintf(stderr, "   Speak Freely, which was built with encryption\n");
  871.         fprintf(stderr, "   removed to permit redistribution without concern\n");
  872.         fprintf(stderr, "   for export control and other regulations.\n");
  873.         fprintf(stderr, "   You can download a version of Speak Freely which\n");
  874.         fprintf(stderr, "   includes full encryption from:\n");
  875.         fprintf(stderr, "       http://www.fourmilab.ch/speakfree/unix/\n");
  876.     }
  877. #endif
  878.  
  879.     /* If message is compressed, decompress appropriately. */
  880.  
  881.     if (msg->compression & fCompVOX) {
  882.     vox_gsmdecomp(msg);
  883.     len = msg->buffer.buffer_len;
  884.     }
  885.  
  886.     if (msg->compression & fCompGSM) {
  887.     gsmdecomp(msg);
  888.     len = msg->buffer.buffer_len;
  889.     }
  890.  
  891.     if (msg->compression & fCompADPCM) {
  892.     adpcmdecomp(msg);
  893.     len = msg->buffer.buffer_len;
  894.     }
  895.  
  896.     if (msg->compression & fCompLPC) {
  897.     lpcdecomp(msg, c);
  898.     len = msg->buffer.buffer_len;
  899.     }
  900.  
  901.     if (msg->compression & fCompLPC10) {
  902.     lpc10decomp(msg, c);
  903.     len = msg->buffer.buffer_len;
  904.     }
  905.  
  906.     if (msg->compression & fComp2X) {
  907.     int is = len, os = len * 2;
  908.  
  909.     rate_flow(val, auxbuf, &is, &os);
  910.     len = os;
  911.     val = auxbuf;
  912.     }
  913.  
  914.     /* If the jitter idle time has elapsed, reset the jitter
  915.        wait to queue the start of this packet sequence. */
  916.  
  917.     if (jitter > 0 && jitteridle == 0 && jitterwait == 0) {
  918.     jitterwait = jitter;
  919.     if (Debug) {
  920.             fprintf(stderr, "%s: starting %ld millisecond jitter delay.\n", prog, jitterwait / 1000L);
  921.     }
  922.     }
  923.  
  924.     /* Receipt of any sound buffer resets the jitter idle timer. */
  925.  
  926.     jitteridle = jitteridlet;          /* Reset jitter idle countdown */
  927.  
  928.     /* If the jitter wait has not yet expired, add the samples to
  929.        the queue waiting to be played at the end of the jitter
  930.        wait.  */
  931.  
  932.     if (jitterwait > 0) {
  933.     struct jitterbuf *jb;
  934.  
  935.     jb = (struct jitterbuf *) malloc(sizeof(struct jitterbuf) + len);
  936.     if (jb != NULL) {
  937.         bcopy(val, jb->value, len);
  938.         jb->length = len;
  939.         jb->next = NULL;
  940.         if (jittail != NULL) {
  941.         jittail->next = jb;
  942.         }
  943.         jittail = jb;
  944.         if (jithead == NULL) {
  945.         jithead = jb;
  946.         windtimer();
  947.         }
  948.         if (Debug) {
  949.                 fprintf(stderr, "%s: adding %d samples to jitter queue.\n",
  950.             prog, len);
  951.         }
  952.     }
  953.     } else {
  954.     flushjitter();
  955.     if (audiok) {
  956.         soundplay(len, val);
  957.     }
  958.     }
  959.     if (record != NULL) {
  960.     fwrite(val, len, 1, record);
  961.     }
  962. }
  963.  
  964. /*  PROGNAME  --  Extract program name from argv[0].  */
  965.  
  966. static char *progname(arg)
  967.   char *arg;
  968. {
  969.     char *cp = strrchr(arg, '/');
  970.  
  971.     return (cp != NULL) ? cp + 1 : arg;
  972. }
  973.  
  974. /*  USAGE  --  Print how-to-call information.  */
  975.  
  976. static void usage()
  977. {
  978.     V fprintf(stderr, "%s  --  Speak Freely sound receiver.\n", prog);
  979.     V fprintf(stderr, "               %s.\n", Relno);
  980.     V fprintf(stderr, "\n");
  981.     V fprintf(stderr, "Usage: %s [options]\n", prog);
  982.     V fprintf(stderr, "Options:\n");
  983.     V fprintf(stderr, "           -A\"file command\" Create answer command in file\n");
  984.     V fprintf(stderr, "           -B\"command\"      Execute command for busy signal\n");
  985. #ifdef CRYPTO
  986.     V fprintf(stderr, "           -BFkey           Blowfish decrypt with key\n");
  987. #endif
  988.     V fprintf(stderr, "           -D               Force debug output\n");
  989.     V fprintf(stderr, "           -E\"command\"      Execute command on incoming call\n");
  990. #ifdef CRYPTO
  991.     V fprintf(stderr, "           -Ikey            IDEA decrypt with key\n");
  992. #endif
  993.     V fprintf(stderr, "           -Jwait,idle      Jitter delay wait and idle in milliseconds\n");
  994. #ifdef CRYPTO
  995.     V fprintf(stderr, "           -Kkey            DES decrypt with key\n");
  996. #endif
  997. #ifdef MULTICAST
  998.     V fprintf(stderr, "           -Mhost/ip        Join multicast to given name or IP address\n");
  999. #endif
  1000.     V fprintf(stderr, "           -N               Disable remote ring requests\n");
  1001. #ifdef CRYPTO
  1002.     V fprintf(stderr, "           -Ofile           Use file as key file\n");
  1003. #endif
  1004.     V fprintf(stderr, "           -Pport           Listen on given port\n");
  1005.     V fprintf(stderr, "           -Q               Prevent debug output\n");
  1006.     V fprintf(stderr, "           -R[+]file        Record [append] sound in file\n");
  1007.     V fprintf(stderr, "           -U               Print this message\n");
  1008.     V fprintf(stderr, "           -Vtimeout        Show hostnames that connect\n");
  1009.     V fprintf(stderr, "           -W               Publish LWL information for sfvod\n");
  1010. #ifdef HEXDUMP
  1011.     V fprintf(stderr, "           -X               Dump packets in hex\n");
  1012. #endif
  1013. #ifdef AUDIO_DEVICE_FILE
  1014.     V fprintf(stderr, "           -Youtdev[:ctldev] Override default audio device file name or specify open #fd\n");
  1015. #endif
  1016. #ifdef CRYPTO
  1017.     V fprintf(stderr, "           -Z\"phrase\"       Set PGP secret key pass phrase\n");
  1018. #endif
  1019.     V fprintf(stderr, "\n");
  1020.     V fprintf(stderr, "by John Walker\n");
  1021.     V fprintf(stderr, "   http://www.fourmilab.ch/\n");
  1022. #ifndef CRYPTO
  1023.     V fprintf(stderr, "\n");
  1024.     V fprintf(stderr, "Note: This version of Speak Freely was built with\n");
  1025.     V fprintf(stderr, "      encryption code removed to permit redistribution\n");
  1026.     V fprintf(stderr, "      without concern for export control and regulations\n");
  1027.     V fprintf(stderr, "      concerning encryption technology in some jurisdictions.\n");
  1028.     V fprintf(stderr, "      You can download a version of Speak Freely with\n");
  1029.     V fprintf(stderr, "      full encryption from:\n");
  1030.     V fprintf(stderr, "             http://www.fourmilab.ch/speakfree/unix/\n");
  1031. #endif
  1032. }
  1033.  
  1034. /*  Main program.  */
  1035.  
  1036. main(argc, argv)
  1037.   int argc;
  1038.   char *argv[];
  1039. {
  1040.     int i, j, k, l, length;
  1041.     struct soundbuf sb;
  1042.     FILE *fp;
  1043.     struct connection *c;
  1044.     char *cp;
  1045.     int newconn, wasrtp;
  1046.     struct auhdr {              /* .au file header */
  1047.     char magic[4];
  1048.     long hsize, dsize, emode, rate, nchan;
  1049.     };
  1050.     static struct auhdr afh = { ".snd", sizeof(struct auhdr), 1, 1, 8000, 1 };
  1051.  
  1052.     prog = progname(argv[0]);
  1053.  
  1054.     /* First pass option processing.  We have to first scan
  1055.        the options to handle any which affect creation of the
  1056.        socket.    On the second pass we can assume the socket
  1057.        already exists, allowing us to join multicast groups,
  1058.        etc. */
  1059.  
  1060.     for (i = 1; i < argc; i++) {
  1061.     char *op, opt;
  1062.  
  1063.     op = argv[i];
  1064.         if (*op == '-') {
  1065.         opt = *(++op);
  1066.         if (islower(opt)) {
  1067.         opt = toupper(opt);
  1068.         }
  1069.  
  1070.         switch (opt) {
  1071.  
  1072.                 case 'D':             /* -D  --  Force debug output */
  1073.             debugforce = TRUE;
  1074.             break;
  1075.  
  1076.                 case 'P':             /* -Pport  --  Port to listen on */
  1077.             if (op[1] != 0) {
  1078.             whichport = atoi(op + 1);
  1079.             }
  1080.             break;
  1081.  
  1082.                 case 'U':             /* -U  --  Print usage information */
  1083.                 case '?':             /* -?  --  Print usage information */
  1084.             usage();
  1085.             return 0;
  1086.  
  1087.                 case 'W':           /* -Wport  --  Publish LWL information for sfvod */
  1088.             lwlonly = TRUE;
  1089.             if (op[1] != 0) {
  1090.             whichport = atoi(op + 1);
  1091.             }
  1092.             break;
  1093.         }
  1094.     } else {
  1095.         usage();
  1096.         return 2;
  1097.     }
  1098.     }
  1099.  
  1100.     if (!lwlonly) {
  1101.  
  1102.     /* Create the sockets from which to read */
  1103.  
  1104.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  1105.     if (sock < 0) {
  1106.             perror("opening data socket");
  1107.         return 1;
  1108.     }
  1109.  
  1110.     ssock = socket(AF_INET, SOCK_DGRAM, 0);
  1111.     if (ssock < 0) {
  1112.             perror("opening control socket");
  1113.         return 1;
  1114.     }
  1115.  
  1116.     /* Create name with wildcards. */
  1117.  
  1118.     name.sin_family = AF_INET;
  1119.     name.sin_addr.s_addr = INADDR_ANY;
  1120.     name.sin_port = htons(whichport);
  1121.     if (bind(sock, (struct sockaddr *) &name, sizeof name) < 0) {
  1122.             perror("binding data socket");
  1123.         return 1;
  1124.     }
  1125.     name.sin_port = htons(whichport + 1);
  1126.     if (bind(ssock, (struct sockaddr *) &name, sizeof name) < 0) {
  1127.             perror("binding control socket");
  1128.         return 1;
  1129.     }
  1130.     name.sin_port = htons(whichport);
  1131.  
  1132.     /*  Process command line options.  */
  1133.  
  1134.         pgppass = getenv("PGPPASS");
  1135.  
  1136. #if Internet_Port != 2074
  1137.     /* This is a reminder to the author who frequently tests with
  1138.        non-standard ports to avoid inadvertently releasing a
  1139.        production version configured for the wrong port. */
  1140.         fprintf(stderr, "%s: warning, listening on non-standard Internet port %d\n",
  1141.         prog, Internet_Port);
  1142. #endif
  1143.  
  1144.     for (i = 1; i < argc; i++) {
  1145.         char *op, opt;
  1146.  
  1147.         op = argv[i];
  1148.             if (*op == '-') {
  1149.         opt = *(++op);
  1150.         if (islower(opt)) {
  1151.             opt = toupper(opt);
  1152.         }
  1153.  
  1154.         switch (opt) {
  1155.  
  1156.                     case 'A':             /* -A"file command"  --  Create reply command on connect */
  1157.             {
  1158.                             char *cp = strchr(op + 1, ' ');
  1159.  
  1160.                 if (cp != NULL) {
  1161.                 replycmd = cp + 1;
  1162.                 *cp = 0;
  1163.                 }
  1164.                 replyfile = op + 1;
  1165.             }
  1166.             break;
  1167.  
  1168.                     case 'E':             /* -E"command"  --  Execute command on connect */
  1169.             replycmdexe = op + 1;
  1170.             break;
  1171.  
  1172.                     case 'B':             /* -B"command"  --  Execute command for busy signal. */
  1173. #ifdef CRYPTO
  1174.                       /* -BFkey  -- Set Blowfish key */
  1175.                         if (ucase(op[1]) == 'F') {
  1176.                 if (strlen(op + 2) == 0) {
  1177.                 blowfish_spec = FALSE;
  1178.                 } else {
  1179.                 struct MD5Context md5c;
  1180.                 unsigned char bfvec[16];
  1181.  
  1182.                 blowfish_spec = TRUE;
  1183.                 MD5Init(&md5c);
  1184.                 MD5Update(&md5c, op + 2, strlen(op + 2));
  1185.                 MD5Final(bfvec, &md5c);
  1186.                 BF_set_key(&blowfishkey, 16, bfvec);
  1187.                 if (Debug) {
  1188.                                     fprintf(stderr, "Blowfish key:");
  1189.                     for (j = 0; j < 16; j++) {
  1190.                                         fprintf(stderr, " %02X", (bfvec[j] & 0xFF));
  1191.                     }
  1192.                                     fprintf(stderr, "\n");
  1193.                 }
  1194.                 }
  1195.             } else
  1196. #endif
  1197.             {
  1198.                 if (strlen(op + 1) > 0) {
  1199.                                 if (!strstr(op + 1, "%s")) {
  1200.                     fprintf(stderr,
  1201.   "%s: invalid -B option command: must contain %%s for IP address insertion.\n",
  1202.                       prog);
  1203.                 } else {
  1204.                     busysignal = op + 1;
  1205.                     dobusy = TRUE;
  1206.                 }
  1207.                 } else {
  1208.                 dobusy = TRUE;
  1209.                 }
  1210.             }
  1211.             break;
  1212.  
  1213. #ifdef CRYPTO
  1214.                     case 'I':             /* -Ikey  --  Set IDEA key */
  1215.             if (strlen(op + 1) == 0) {
  1216.                 ideakey[0] = FALSE;
  1217.             } else {
  1218.                 struct MD5Context md5c;
  1219.  
  1220.                 MD5Init(&md5c);
  1221.                 MD5Update(&md5c, op + 1, strlen(op + 1));
  1222.                 MD5Final(ideakey + 1, &md5c);
  1223.                 ideakey[0] = TRUE;
  1224.                 if (Debug) {
  1225.                                 fprintf(stderr, "IDEA key:");
  1226.                 for (j = 0; j < 16; j++) {
  1227.                                     fprintf(stderr, " %02X", (ideakey[j + 1] & 0xFF));
  1228.                 }
  1229.                                 fprintf(stderr, "\n");
  1230.                 }
  1231.             }
  1232.             break;
  1233. #endif
  1234.  
  1235.                     case 'J':             /* -Jwait,idle --  Set jitter wait and idle times */
  1236.             if (isdigit(*(op + 1))) {
  1237.                             char *cp = strchr(op + 1, ',');
  1238.  
  1239.                 if (cp != NULL) {
  1240.                 *cp = 0;
  1241.                 }
  1242.                 jitter = atoi(op + 1) * 1000L;
  1243.                 jitteridlet = (cp == NULL) ? (jitter * 2) :
  1244.                 (atoi(cp + 1) * 1000L);
  1245.                 if (jitter < 250000) {
  1246.                 fprintf(stderr,
  1247.                      "%s: invalid jitter wait %d--reset to 250 milliseconds.\n",
  1248.                     prog, jitter / 1000);
  1249.                 jitter = 250000;
  1250.                 }
  1251.                 if (jitteridlet < 250000) {
  1252.                 fprintf(stderr,
  1253.                      "%s: invalid jitter idle time %d--reset to 250 milliseconds.\n",
  1254.                     prog, jitteridlet / 1000);
  1255.                 jitteridlet = 250000;
  1256.                 }
  1257.             } else {
  1258.                 jitteridlet = 2 * (jitter = 1000000L);
  1259.             }
  1260.             break;
  1261.  
  1262. #ifdef CRYPTO
  1263.                     case 'K':             /* -Kkey  --  Set DES key */
  1264.             desinit(1);      /* Initialise the DES library */
  1265.             if (strlen(op + 1) == 0) {
  1266.                 deskey[0] = rtpdeskey[0] = vatdeskey[0] = FALSE;
  1267.             } else {
  1268.                 struct MD5Context md5c;
  1269.                 char md5key[16], algorithm[16];
  1270.  
  1271.                 MD5Init(&md5c);
  1272.                 MD5Update(&md5c, op + 1, strlen(op + 1));
  1273.                 MD5Final(md5key, &md5c);
  1274.                 for (j = 0; j < 8; j++) {
  1275.                 deskey[j + 1] = (char)
  1276.                           ((md5key[j] ^ md5key[j + 8]) & 0x7F);
  1277.                 }
  1278.                 deskey[0] = TRUE;
  1279.                 des_string_to_key(op + 1, (des_cblock *) (vatdeskey + 1));
  1280.                 string_DES_key(op + 1, rtpdeskey + 1, algorithm);
  1281.                             if (strcmp(algorithm, "DES-CBC") != 0) {
  1282.                                 fprintf(stderr, "Unsupported encryption algorithm: %s.  Only DES-CBC is available.\n",
  1283.                     algorithm);
  1284.                 return 2;
  1285.                 }
  1286.                 rtpdeskey[0] = vatdeskey[0] = TRUE;
  1287.                 if (Debug) {
  1288.                                 fprintf(stderr, "DES key:");
  1289.                 for (j = 0; j < 8; j++) {
  1290.                                     fprintf(stderr, " %02X", (deskey[j + 1] & 0xFF));
  1291.                 }
  1292.                                 fprintf(stderr, "\n");
  1293.                                 fprintf(stderr, "RTP key:");
  1294.                 for (j = 0; j < 8; j++) {
  1295.                                     fprintf(stderr, " %02X", (rtpdeskey[j + 1] & 0xFF));
  1296.                 }
  1297.                                 fprintf(stderr, "\n");
  1298.                                 fprintf(stderr, "VAT key:");
  1299.                 for (j = 0; j < 8; j++) {
  1300.                                     fprintf(stderr, " %02X", (vatdeskey[j + 1] & 0xFF));
  1301.                 }
  1302.                                 fprintf(stderr, "\n");
  1303.                 }
  1304.             }
  1305.             break;
  1306. #endif
  1307.  
  1308. #ifdef MULTICAST
  1309.                     case 'M':             /* -Mhost/ip -- Join multicast to name/IP number */
  1310.             {
  1311.                 struct ip_mreq m;
  1312.                 struct hostent *h;
  1313.                 long naddr;
  1314.  
  1315.                             /* If it's a valid IP number, use it.  Otherwise try to look
  1316.                    up as a host name. */
  1317.  
  1318.                 if ((naddr = inet_addr(op + 1)) == -1) {
  1319.                 h = gethostbyname(op + 1);
  1320.                 if (h == 0) {
  1321.                                     fprintf(stderr, "%s: unknown multicast group\n", op + 1);
  1322.                     return 2;
  1323.                 }
  1324.                 bcopy((char *) h->h_addr, (char *) &naddr, sizeof naddr);
  1325.                 }
  1326.                 m.imr_multiaddr.s_addr = naddr;
  1327.                 m.imr_interface.s_addr = htons(INADDR_ANY);
  1328.                 if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  1329.                 (char *) &m, sizeof m) < 0) {
  1330.                                 perror("joining multicast group");
  1331.                 return 2;
  1332.                 }
  1333.             }
  1334.             break;
  1335. #endif
  1336.  
  1337.                     case 'N':             /* -N  --  Disable remote ring requests */
  1338.             noring = TRUE;
  1339.             break;
  1340.  
  1341. #ifdef CRYPTO
  1342.                     case 'O':             /* -Ofile -- Use file as key file */
  1343.                         fp = fopen(op + 1, "r");
  1344.             if (fp == NULL) {
  1345.                             perror("Cannot open key file");
  1346.                 return 2;
  1347.             }
  1348.             curotp = malloc(BUFL);
  1349.             if (curotp == NULL) {
  1350.                             fprintf(stderr, "%s: Cannot allocate key file buffer.\n", prog);
  1351.                 return 2;
  1352.             }
  1353.             l = fread(curotp, 1, BUFL, fp);
  1354.             if (l == 0) {
  1355.                             /* Idiot supplied void key file.  Give 'im
  1356.                    what he asked for: no encryption. */
  1357.                 curotp[0] = 0;
  1358.                 l = 1;
  1359.             }
  1360.             fclose(fp);
  1361.             /* If the file is shorter than the maximum buffer
  1362.                we may need to encrypt, replicate the key until
  1363.                the buffer is filled. */
  1364.             j = l;
  1365.             k = 0;
  1366.             while (j < BUFL) {
  1367.                 curotp[j++] = curotp[k++];
  1368.                 if (k >= l) {
  1369.                 k = 0;
  1370.                 }
  1371.             }
  1372.             break;
  1373. #endif
  1374.  
  1375.                     case 'Q':             /* -Q  --  Prevent debug output */
  1376.             debugforce = -1;
  1377.             break;
  1378.  
  1379.                     case 'R':             /* -Rfile  --  Answering machine record */
  1380.             {
  1381.                 char *fn = op + 1;
  1382.                 int append = FALSE;
  1383.  
  1384.                             if (*fn == '+') {
  1385.                 fn++;
  1386.                 append = TRUE;
  1387.                 }
  1388.                             record = fopen(fn, append ? "a" : "w");
  1389.                 if (record == NULL) {
  1390.                                 perror("Cannot create answering machine file");
  1391.                 return 2;
  1392.                 }
  1393.                 fseek(record, 0L, 2);
  1394.                 if (ftell(record) == 0) {
  1395.                 fwrite(&afh, sizeof afh, 1, record);
  1396.                 }
  1397.                 fflush(record);
  1398.             }
  1399.             break;
  1400.  
  1401.                     case 'V':             /* -Vtimeout  --  Show hostnames that connect */
  1402.             showhosts = TRUE;
  1403.             if (op[1] != 0) {
  1404.                 int t = atoi(op + 1) * 1000000L;
  1405.  
  1406.                 if (t > 0) {
  1407.                 if (t < (TickTock + 1)) {
  1408.                     t = TickTock + 1;
  1409.                 }
  1410.                 hosttimeout = (t / TickTock) * TickTock;
  1411.                 }
  1412.             }
  1413.             break;
  1414.  
  1415. #ifdef HEXDUMP
  1416.                     case 'X':             /* -X  --  Dump packets in hex */
  1417.             hexdump = debugforce = TRUE;
  1418.             break;
  1419. #endif
  1420.  
  1421. #ifdef AUDIO_DEVICE_FILE
  1422.                 case 'Y':             /* -Youtdev:[ctldev] -- Specify audio
  1423.                              output and control device
  1424.                              file names or #open_fd. */
  1425.             devAudioOutput = op + 1;
  1426.                     if (strchr(op + 1, ':') != NULL) {
  1427.                         devAudioControl = strchr(op + 1, ':') + 1;
  1428.             }
  1429.             break;
  1430. #endif
  1431.  
  1432. #ifdef CRYPTO
  1433.                     case 'Z':             /* -Z"phrase"  --  Set PGP pass phrase */
  1434.             if (op[1] != 0) {
  1435.                 pgppass = strdup(op + 1);
  1436.                 op = argv[i];
  1437.                             /* Zap the pass phrase in memory so "ps" etc. don't see it. */
  1438.                 while (*op != 0) {
  1439.                                 *op++ = ' ';
  1440.                 }
  1441.             } else {
  1442.                 char s[256];
  1443.  
  1444.                             fprintf(stderr, "PGP secret key pass phrase: ");
  1445.                 fflush(stderr);
  1446.                 initscr();
  1447.                 noecho();
  1448.                 getstr(s);
  1449.                 pgppass = strdup(s);
  1450.                 echo();
  1451.                 endwin();
  1452.                             fprintf(stderr, "\n");
  1453.             }
  1454.             break;
  1455. #endif
  1456.         }
  1457.         }
  1458.     }
  1459.  
  1460. #ifdef HALF_DUPLEX
  1461.     {
  1462. #ifndef INADDR_LOOPBACK
  1463.     /* The standard local host loopback address is supposed to be
  1464.        defined in <netinet/in.h>, but just in case some screwball
  1465.            system doesn't, let's include our own definition here. */
  1466. #define INADDR_LOOPBACK  0x7F000001
  1467. #endif
  1468.     localhost.s_addr = htonl(INADDR_LOOPBACK);
  1469. #ifdef HDX_DEBUG
  1470.         if (Debug) {
  1471.                 fprintf(stderr, "%s: local host %s\n", prog,
  1472.                inet_ntoa(localhost));
  1473.         }
  1474. #endif
  1475.     }
  1476. #endif
  1477.  
  1478. #ifdef LINUX_FPU_FIX
  1479.     __setfpucw(_FPU_IEEE);          /* Mask floating point interrupts to
  1480.                      enable standard IEEE processing.
  1481.                      Current libc releases do this by
  1482.                      default, so this is needed only on
  1483.                      older libraries. */
  1484. #endif
  1485.  
  1486.     rate_start(4000, 8000);
  1487.  
  1488.     /* Initialise GSM decoding. */
  1489.  
  1490.     gsmh = gsm_create();
  1491.  
  1492.     /* Initialise LPC decoding. */
  1493.  
  1494.     if (!lpc_start()) {
  1495.             fprintf(stderr, "Cannot allocate LPC decoding memory.\n");
  1496.         return 1;
  1497.     }
  1498.     lpc10init();
  1499.  
  1500.     /* Find assigned port value and print it. */
  1501.  
  1502.     length = sizeof(name);
  1503.     if (getsockname(sock, (struct sockaddr *) &name, &length) < 0) {
  1504.             perror("getting socket name");
  1505.         return 1;
  1506.     }
  1507. #ifdef SHOW_SOCKET
  1508.         fprintf(stderr, "%s: socket port #%d\n", prog, ntohs(name.sin_port));
  1509. #endif
  1510.     }
  1511.  
  1512.     /* Contact look who's listening host, if requested. */
  1513.  
  1514.     cp = getenv("SPEAKFREE_LWL_TELL");
  1515.     if (cp != NULL) {
  1516.     struct hostent *h;
  1517.     char md5key[16];
  1518.     char *ep, *np;
  1519.     long iadr;
  1520.     int n;
  1521.  
  1522.     makeSessionKey(md5key);
  1523.     bcopy(md5key, (char *) &ssrc, sizeof ssrc);
  1524.     sdesl = rtp_make_sdes(&sdes, ssrc, whichport, FALSE);
  1525.     lookhost.sin_family = AF_INET;
  1526.  
  1527.     while (lwl_nsites < LWL_MAX_SITES) {
  1528.         n = lwl_nsites;
  1529.         while (*cp != 0 && isspace(*cp)) {
  1530.         cp++;
  1531.         }
  1532.         if (*cp == 0) {
  1533.         break;
  1534.         }
  1535.             if ((np = strchr(cp, ',')) != NULL) {
  1536.         *np++ = 0;
  1537.         }
  1538.         lwl_ports[lwl_nsites] = Internet_Port + 2;
  1539.         lwl_strikes[lwl_nsites] = 0; /* Clear strikeout counter */
  1540.             if ((ep = strchr(cp, ':')) != NULL) {
  1541.         *ep = 0;
  1542.         lwl_ports[lwl_nsites] = atoi(ep + 1);
  1543.         }
  1544.         if (isdigit(*cp) && (iadr = inet_addr(cp)) != -1) {
  1545.         bcopy((char *) &iadr, (char *) (&lwl_sites[lwl_nsites]),
  1546.               sizeof iadr);
  1547.         lwl_nsites++;
  1548.         } else {
  1549.         h = gethostbyname(cp);
  1550.         if (h != NULL) {
  1551.             bcopy((char *) (h->h_addr),
  1552.               (char *) (&lwl_sites[lwl_nsites]),
  1553.               sizeof(unsigned long));
  1554.             lwl_nsites++;
  1555.         } else {
  1556.                     fprintf(stderr, "%s: warning, SPEAKFREE_LWL_TELL host %s unknown.\n",
  1557.             prog, cp);
  1558.         }
  1559.         }
  1560.         if (Debug && lwl_nsites > n) {
  1561.                 fprintf(stderr, "%s: publishing on LWL server %s: %s.\n", prog,
  1562.             inet_ntoa(lwl_sites[n]), cp);
  1563.         }
  1564.         if (np == NULL) {
  1565.         break;
  1566.         }
  1567.         cp = np;
  1568.     }
  1569.     if (lwl_nsites > 0) {
  1570.         sendLwlMessage(FALSE);
  1571.     }
  1572.     }
  1573.  
  1574.     /*    See if the user has specified a face file.  If so,
  1575.     try to open it.  */
  1576.  
  1577.     if (!lwlonly) {
  1578.         char *cp = getenv("SPEAKFREE_FACE");
  1579.  
  1580.     if (cp != NULL) {
  1581.             if ((facefile = fopen(cp, "r")) == NULL) {
  1582.                 fprintf(stderr, "%s: cannot open SPEAKFREE_FACE file %s\n",
  1583.             prog, cp);
  1584.         }
  1585.     }
  1586.     }
  1587.  
  1588.     signal(SIGHUP, exiting);          /* Set signal to handle termination */
  1589.     signal(SIGINT, exiting);          /* Set signal to handle termination */
  1590.     signal(SIGTERM, exiting);          /* Set signal to handle termination */
  1591.     signal(SIGALRM, release);          /* Set signal to handle timeout */
  1592.     signal(SIGCHLD, viewerterm);      /* Set signal to handle face viewer termination */
  1593.     windtimer();              /* Set periodic status update  */
  1594.  
  1595.     /* If all we're doing is broadcasting a periodic LWL update
  1596.        for sfvod, simply sit in a timer loop forever and let the
  1597.        SIGALRM handler take care of business. */
  1598.  
  1599.     while (lwlonly) {
  1600.     if (lwl_nsites == 0) {
  1601.         /* -W option but no valid sites found.  Exit with error
  1602.            status. */
  1603.         return 2;
  1604.     }
  1605.     pause();
  1606.     }
  1607.  
  1608.     /* Read from the socket. */
  1609.  
  1610.     while (TRUE) {
  1611.     fd_set fdset;
  1612.     int wsock, control, busyreject;
  1613.  
  1614.     FD_ZERO(&fdset);
  1615.     FD_SET(sock, &fdset);
  1616.     FD_SET(ssock, &fdset);
  1617.     if (select(FD_SETSIZE, &fdset, NULL, NULL, NULL) <= 0) {
  1618.         continue;
  1619.     }
  1620.     wsock = FD_ISSET(sock, &fdset) ? sock :
  1621.             (FD_ISSET(ssock, &fdset) ? ssock : -1);
  1622.     if (wsock < 0) {
  1623.         continue;
  1624.     }
  1625.     control = wsock == ssock;
  1626.     fromlen = sizeof(from);
  1627.     if ((rll = recvfrom(wsock, (char *) &sb, sizeof sb, 0, (struct sockaddr *) &from, &fromlen)) < 0) {
  1628.         if (errno != EINTR) {
  1629.                 perror(!control ? "receiving data packet" :
  1630.                                   "receiving control packet");
  1631.         }
  1632.         continue;
  1633.     }
  1634. #ifdef HEXDUMP
  1635.     if (hexdump) {
  1636.             fprintf(stderr, "%s: %d bytes read from %s socket.\n", prog, rll,
  1637.                     control ? "control" : "data");
  1638.         xd(stderr, &sb, rll, TRUE);
  1639.     }
  1640. #endif
  1641.  
  1642.     /* See if this connection is active.  If not, initialise a new
  1643.        connection. */
  1644.  
  1645.     busyreject = FALSE;
  1646.     newconn = FALSE;
  1647.     c = conn;
  1648.     while (c != NULL) {
  1649.         if (memcmp(&from.sin_addr, &(c->con_addr),
  1650.                sizeof(struct in_addr)) == 0) {
  1651.         break;
  1652.         }
  1653.         c = c->con_next;
  1654.     }
  1655.     if (c == NULL) {
  1656.         c = (struct connection *) malloc(sizeof(struct connection));
  1657.         if (c != NULL) {
  1658.         struct hostent *h;
  1659.  
  1660.         newconn = TRUE;
  1661.         c->con_next = conn;
  1662.         c->pgpkey[0] = FALSE;
  1663.         bzero(c->keymd5, 16);
  1664.         c->con_uname[0] = c->con_email[0] = 0;
  1665. #ifndef CRYPTO
  1666.         c->con_crypt_warning = FALSE;
  1667. #endif
  1668.         conn = c;
  1669.         bcopy(&from.sin_addr, &(c->con_addr),
  1670.             sizeof(struct in_addr));
  1671.         h = gethostbyaddr((char *) &from.sin_addr, sizeof(struct in_addr),
  1672.                   AF_INET);
  1673.         if (h == NULL) {
  1674.             strcpy(c->con_hostname, inet_ntoa(from.sin_addr));
  1675.         } else {
  1676.             strcpy(c->con_hostname, h->h_name);
  1677.         }
  1678.         }
  1679.     } else if (c->con_timeout == -1) {
  1680.         newconn = TRUE;
  1681.     }
  1682.  
  1683.     /* Initialise fields in connection.  Only fields which need to
  1684.        be reinitialised when a previously idle host resumes activity
  1685.        need be set here. */
  1686.  
  1687.     if (newconn) {
  1688.         c->face_file = NULL;
  1689.         c->face_filename[0] = 0;
  1690.         c->face_viewer = 0;
  1691.         c->face_stat = FSinit;
  1692.         c->face_address = 0L;
  1693.         c->face_retry = 0;
  1694.         c->con_compmodes = -1;
  1695.         c->con_protocol = PROTOCOL_UNKNOWN;
  1696.         c->con_rseq = -1;
  1697.         c->con_reply_current = FALSE;
  1698.         c->con_busy = 0;
  1699.             bcopy("\221\007\311\201", c->con_session, 4);
  1700.         lpc_init(&c->lpcc);
  1701.         busyreject = isBusy();
  1702.     }
  1703.  
  1704.     if (c != NULL) {
  1705.         /* Reset connection timeout. */
  1706.         c->con_timeout = 0;
  1707.  
  1708.             /* If we're rejecting this with a busy signal, start
  1709.            the busy timeout running and dispatch the busy
  1710.            signal to the host. */
  1711.  
  1712.         if (busyreject && c->con_busy == 0) {
  1713.         pid_t cpid;
  1714.  
  1715.         c->con_busy = busytimeout;
  1716.  
  1717.         if (audiok) {
  1718.             soundterm();
  1719.             audiok = FALSE;
  1720.             if (Debug) {
  1721.                          fprintf(stderr, "%s: releasing audio before busy signal fork().\n", prog);
  1722.             }
  1723.         }
  1724.         cpid = fork();
  1725.         if (cpid == 0) {
  1726.             char s[256];
  1727.  
  1728.             signal(SIGHUP, SIG_DFL);
  1729.             signal(SIGINT, SIG_DFL);
  1730.             signal(SIGTERM, SIG_DFL);
  1731.             signal(SIGALRM, SIG_DFL);
  1732.             signal(SIGCHLD, SIG_DFL);
  1733.  
  1734.             /* Now we need to close any shared resources
  1735.                that might have been inherited from the parent
  1736.                process to avoid their being locked up for the
  1737.                duration of the child process execution. */
  1738.  
  1739.             close(sock);
  1740.             if (record != NULL) {
  1741.             fclose(record);
  1742.             }
  1743.             if (facefile != NULL) {
  1744.             fclose(facefile);
  1745.             }
  1746.             sprintf(s, busysignal, inet_ntoa(from.sin_addr));
  1747.             if (Debug) {
  1748.                         fprintf(stderr, "%s: sending busy signal with %s\n",
  1749.                 prog, s);
  1750.             }
  1751.             system(s);
  1752.             exit(0);
  1753.         } else if (cpid == (pid_t) -1) {
  1754.                     perror("creating busy signal process");
  1755.         }
  1756.         }
  1757.  
  1758.         if (newconn) {
  1759.         if (showhosts) {
  1760.                     fprintf(stderr, "%s: %s %s %s\n", prog, etime(),
  1761.                 c->con_hostname,
  1762.                             busyreject ? "sending busy signal" : "connect");
  1763.         }
  1764.         }
  1765.         if (busyreject) {
  1766.         continue;
  1767.         }
  1768.  
  1769.         /* Request face data from the other end, starting with
  1770.            block zero.  If the connection was created itself
  1771.                by a face data request, don't request the face from
  1772.            the other end; wait, instead, for some sound to
  1773.            arrive.    We use face_stat to decide when to make the
  1774.            request rather than newconn, since a connection may
  1775.            have been created by a face request from the other
  1776.                end, which didn't trigger a reciprocal request by
  1777.            us. */
  1778.  
  1779.         if (!control && (c->con_protocol == PROTOCOL_SPEAKFREE) &&
  1780.             (c->face_stat == FSinit) &&
  1781.             isSoundPacket(ntohl(sb.compression)) &&
  1782.             (ntohl(sb.compression) & fFaceOffer)) {
  1783.         c->face_address = 0;
  1784.         c->face_timeout = 0;
  1785.         c->face_retry = 0;
  1786.         c->face_stat = FSreply;   /* Activate request from timeout */
  1787.         faceTransferActive++;      /* Mark face transfer underway */
  1788.         if (faceTransferActive == 1) {
  1789.             windtimer();      /* Set timer to fast cadence */
  1790.         }
  1791.         }
  1792.  
  1793.     } else {
  1794.         continue;
  1795.     }
  1796.  
  1797.         /* If we've sent the connection a busy signal, ignore all
  1798.        packets from it until the busy timeout expires. */
  1799.  
  1800.     if (c->con_busy > 0) {
  1801.         if (Debug) {
  1802.                 fprintf(stderr, "%s: busy--discarding packet from %s.\n", prog,
  1803.             c->con_hostname);
  1804.         }
  1805.         continue;
  1806.     }
  1807.  
  1808.     wasrtp = FALSE;
  1809.  
  1810. #ifdef CRYPTO
  1811.  
  1812.         /* If a DES key is present and we're talking RTP or VAT
  1813.        protocol we must decrypt the packet at this point.
  1814.        We decrypt the packet if:
  1815.  
  1816.         1.  A DES key was given on the command line, and
  1817.             either:
  1818.  
  1819.             a)    The packet arrived on the control port
  1820.             (and hence must be from an RTP/VAT client), or
  1821.  
  1822.             b)    The protocol has already been detected as
  1823.             RTP or VAT by reception of a valid control
  1824.             port message.  */
  1825.  
  1826.     if ((control || (c->con_protocol == PROTOCOL_RTP) ||
  1827.             (c->con_protocol == PROTOCOL_VAT)) &&
  1828.          rtpdeskey[0]) {
  1829.  
  1830.         /* One more little twist.  If this packet arrived on the
  1831.            control channel, see if it passes all the tests for a
  1832.                valid RTCP packet.  If so, we'll assume it isn't
  1833.            encrypted.  RTP utilities have the option of either
  1834.            encrypting their control packets or sending them in
  1835.            the clear, so a hack like this is the only way we have
  1836.            to guess whether something we receive is encrypted. */
  1837.  
  1838.         if (!isValidRTCPpacket((unsigned char *) &sb, rll)) {
  1839.         des_key_schedule sched;
  1840.         des_cblock ivec;
  1841.         int drll = rll;
  1842.         char *whichkey;
  1843.         static int toggle = 0;
  1844.  
  1845.         bzero(ivec, 8);
  1846.         drll = (rll + 7) & (~7);
  1847.         if (Debug) {
  1848.                     fprintf(stderr, "Decrypting %d VAT/RTP bytes with DES key.\r\n",
  1849.                 drll);
  1850.         }
  1851.         if (drll > rll) {
  1852.             /* Should only happen for VAT protocol.  Zero the rest of
  1853.                the DES encryption block to guarantee consistency. */
  1854.             bzero(((char *) &sb) + rll, drll - rll);
  1855.         }
  1856.  
  1857.         /* If the protocol is unknown, toggle back and forth
  1858.            between the RTP and VAT DES keys until we crack the
  1859.            packet and set the protocol. */
  1860.  
  1861.         if (c->con_protocol == PROTOCOL_UNKNOWN ||
  1862.             c->con_protocol == PROTOCOL_VATRTP_CRYPT ||
  1863.             c->con_protocol == PROTOCOL_SPEAKFREE) {
  1864.             whichkey = toggle == 0 ? vatdeskey :
  1865.                    (toggle == 1 ? rtpdeskey : NULL);
  1866.             toggle = (toggle + 1) % 3;
  1867.         } else {
  1868.             whichkey = c->con_protocol == PROTOCOL_VAT ?
  1869.                 vatdeskey : rtpdeskey;
  1870.         }
  1871.         if (whichkey != NULL) {
  1872.             des_set_key((des_cblock *) (whichkey + 1), sched);
  1873.             des_ncbc_encrypt((des_cblock *) &sb,
  1874.             (des_cblock *) &sb, rll, sched,
  1875.             (des_cblock *) ivec, DES_DECRYPT);
  1876.  
  1877.             /* Just one more thing.  In RTP (unlike VAT), when
  1878.                an RTCP control packet is encrypted, 4 bytes of
  1879.                random data are prefixed to the packet to prevent
  1880.                known-plaintext attacks.  We have to strip this
  1881.                prefix after decrypting. */
  1882.  
  1883.             if (control && ((*(((char *) &sb) + 4) & 0xC0) == 0x80)) {
  1884.             rll -= 4;
  1885.             bcopy(((char *) &sb) + 4, (char *) &sb, rll);
  1886.             }
  1887.         }
  1888. #ifdef HEXDUMP
  1889.         if (hexdump) {
  1890.             xd(stderr, &sb, rll, TRUE);
  1891.         }
  1892. #endif
  1893.         }
  1894.     }
  1895. #endif
  1896.  
  1897.     /* If this packet arrived on the session control port, dispatch
  1898.        it to the appropriate handler for its protocol. */
  1899.  
  1900.     if (control) {
  1901.         short protocol = PROTOCOL_VATRTP_CRYPT;
  1902.         unsigned char *p = (unsigned char *) &sb;
  1903.         unsigned char *apkt;
  1904.         int proto = (p[0] >> 6) & 3;
  1905.  
  1906.         if (proto == 0) {          /* VAT */
  1907.         /* To avoid spoofing by bad encryption keys, require
  1908.                    a proper ID message be seen before we'll flip into
  1909.            VAT protocol. */
  1910.         if (((p[1] == 1) || (p[1] == 3)) ||
  1911.             ((c->con_protocol == PROTOCOL_VAT) && (p[1] == 2))) {
  1912.             protocol = PROTOCOL_VAT;
  1913.             bcopy(p + 2, c->con_session, 2);  /* Save conference ID */
  1914.  
  1915.             if (p[1] == 1 && showhosts) {
  1916.             char uname[256];
  1917.  
  1918.             bcopy(p + 4, uname, rll - 4);
  1919.             uname[rll - 4] = 0;
  1920.             if (strcmp(uname, c->con_uname) != 0) {
  1921.                 strcpy(c->con_uname, uname);
  1922.                             fprintf(stderr, "%s: %s sending from %s.\n", prog,
  1923.                     c->con_uname, c->con_hostname);
  1924.             }
  1925.             }
  1926.  
  1927.             /* Handling of VAT IDLIST could be a lot more elegant
  1928.                than this. */
  1929.  
  1930.             if (p[1] == 3 && showhosts) {
  1931.             char *uname;
  1932.  
  1933.             uname = (char *) malloc(rll);
  1934.             if (uname != NULL) {
  1935.                 unsigned char *bp = p, *ep = p + rll;
  1936.                 int i = bp[4];
  1937.  
  1938.                 bp += 8;
  1939.                 uname[0] = 0;
  1940.                 *ep = 0;
  1941.                 while (--i >= 0 && bp < ep) {
  1942.                 bp += 4;
  1943.                                 strcat(uname, "\t");
  1944.                 strcat(uname, (char *) bp);
  1945.                 while (isspace(uname[strlen(uname) - 1])) {
  1946.                     uname[strlen(uname) - 1] = 0;
  1947.                 }
  1948.                                 strcat(uname, "\n");
  1949.                 bp += (strlen((char *) bp) + 3) & ~3;
  1950.                 }
  1951.                 if (strncmp(uname, c->con_uname, (sizeof c->con_uname - 1)) != 0) {
  1952.                 strncpy(c->con_uname, uname, sizeof c->con_uname);
  1953.                 if (strlen(uname) > ((sizeof c->con_uname) - 1)) {
  1954.                     c->con_uname[((sizeof c->con_uname) - 1)] = 0;
  1955.                 }
  1956.                                 fprintf(stderr, "%s: now in conference at %s:\n%s", prog,
  1957.                     c->con_hostname, uname);
  1958.                 }
  1959.                 free(uname);
  1960.             }
  1961.             }
  1962.  
  1963.                     /* If it's a DONE packet, reset protocol to unknown. */
  1964.  
  1965.             if (p[1] == 2) {
  1966.             c->con_protocol = protocol = PROTOCOL_UNKNOWN;
  1967.             c->con_timeout = hosttimeout - 1;
  1968.             c->con_uname[0] = c->con_email[0] = 0;
  1969.             if (showhosts) {
  1970.                             fprintf(stderr, "%s: %s VAT connection closed.\n",
  1971.                     prog, c->con_hostname);
  1972.             }
  1973.             }
  1974.         }
  1975.  
  1976.         } else if (proto == RTP_VERSION || proto == 1) { /* RTP */
  1977.         if (isValidRTCPpacket((unsigned char *) &sb, rll)) {
  1978.             protocol = (proto == 1) ? PROTOCOL_SPEAKFREE : PROTOCOL_RTP;
  1979.             bcopy(p + 4, c->con_session, 4);  /* Save SSRC */
  1980.  
  1981.                     /* If it's a BYE packet, reset protocol to unknown. */
  1982.  
  1983.             if (isRTCPByepacket((unsigned char *) &sb, rll)) {
  1984.             c->con_protocol = protocol = PROTOCOL_UNKNOWN;
  1985.             c->con_timeout = hosttimeout - 1;
  1986.             c->con_uname[0] = c->con_email[0] = 0;
  1987.             if (showhosts) {
  1988.                             fprintf(stderr, "%s: %s %s connection closed.\n",
  1989.                     prog, c->con_hostname,
  1990.                                     proto == 1 ? "Speak Freely" : "RTP");
  1991.             }
  1992.  
  1993.                     /* If it's a text chat message, print it. */
  1994.  
  1995.             } else if (isRTCPAPPpacket((unsigned char *) &sb, rll,
  1996.                     RTCP_APP_TEXT_CHAT, &apkt) && apkt != NULL) {
  1997.             char *ident = c->con_hostname;
  1998.  
  1999.             /* To identify the sender, get successively more
  2000.                personal depending on the information we have at
  2001.                hand, working down from hostname (which may just
  2002.                            be an IP address if we couldn't resolve the host,
  2003.                through E-mail address, to user name. */
  2004.  
  2005.             if (c->con_email[0] != 0) {
  2006.                 ident = c->con_email;
  2007.             }
  2008.             if (c->con_uname[0] != 0) {
  2009.                 ident = ident = c->con_uname;
  2010.             }
  2011.  
  2012.                         printf("%s: %s\n", ident, (char *) (apkt + 12));
  2013.  
  2014.                     /* Otherwise, it's presumably an SDES, from which we
  2015.                should update the user identity information for the
  2016.                connection. */
  2017.  
  2018.             } else {
  2019.             struct rtcp_sdes_request rp;
  2020.  
  2021.             rp.nitems = 4;
  2022.             rp.item[0].r_item = RTCP_SDES_CNAME;
  2023.             rp.item[1].r_item = RTCP_SDES_NAME;
  2024.             rp.item[2].r_item = RTCP_SDES_EMAIL;
  2025.             rp.item[3].r_item = RTCP_SDES_TOOL;
  2026.             if (parseSDES((unsigned char *) &sb, &rp)) {
  2027.                 char uname[256], email[256];
  2028.  
  2029.                 uname[0] = email[0] = 0;
  2030.                 if (rp.item[1].r_text != NULL) {
  2031.                 copySDESitem(rp.item[1].r_text, uname);
  2032.                 if (rp.item[2].r_text != NULL) {
  2033.                     copySDESitem(rp.item[2].r_text, email);
  2034.                 } else if (rp.item[2].r_text != NULL) {
  2035.                     copySDESitem(rp.item[0].r_text, email);
  2036.                 }
  2037.                 } else if (rp.item[2].r_text != NULL) {
  2038.                 copySDESitem(rp.item[2].r_text, uname);
  2039.                 } else if (rp.item[0].r_text != NULL) {
  2040.                 copySDESitem(rp.item[0].r_text, uname);
  2041.                 }
  2042.                 if (strcmp(uname, c->con_uname) != 0 ||
  2043.                 strcmp(email, c->con_email) != 0) {
  2044.                 strcpy(c->con_uname, uname);
  2045.                 strcpy(c->con_email, email);
  2046.                 if (showhosts && uname[0]) {
  2047.                                     fprintf(stderr, "%s: %s", prog, uname);
  2048.                     if (email[0]) {
  2049.                                       fprintf(stderr, " (%s)", email);
  2050.                     }
  2051.                                     fprintf(stderr, " sending from %s.\n",
  2052.                         c->con_hostname);
  2053.                 }
  2054.                 }
  2055.             }
  2056.             }
  2057.         } else {
  2058.             if (Debug) {
  2059.                         fprintf(stderr, "Invalid RTCP packet received.\n");
  2060.             }
  2061.         }
  2062.         } else {
  2063.         if (Debug) {
  2064.                     fprintf(stderr, "Bogus protocol 3 control message.\n");
  2065.         }
  2066.         }
  2067.  
  2068.         /* If protocol changed, update in connection and, if appropriate,
  2069.            update the reply command. */
  2070.  
  2071.         if (protocol != c->con_protocol) {
  2072.         static char *pname[] = {
  2073.                     "Speak Freely",
  2074.                     "VAT",
  2075.                     "RTP",
  2076.                     "VAT/RTP encrypted",
  2077.                     "Unknown"
  2078.         };
  2079.  
  2080.         c->con_protocol = protocol;
  2081.         if (showhosts) {
  2082.                     fprintf(stderr, "%s: %s sending in %s protocol.\n",
  2083.                 prog, c->con_hostname, pname[protocol]);
  2084.         }
  2085.         c->con_reply_current = FALSE;
  2086.         }
  2087.         continue;
  2088.     }
  2089.  
  2090.     /* If this message is tagged with our Speak Freely protocol
  2091.        bit, force protocol back to Speak Freely.  This allows us
  2092.        to switch back to Speak Freely after receiving packets in
  2093.        VAT.  We can still get confused if we receive a packet from
  2094.            an older version of Speak Freely that doesn't tag. */
  2095.  
  2096.     if (c->con_protocol == PROTOCOL_VAT ||
  2097.         c->con_protocol == PROTOCOL_VATRTP_CRYPT) {
  2098.         unsigned char *p = (unsigned char *) &sb;
  2099.  
  2100.         if (((p[0] >> 6) & 3) == 1) {
  2101.         c->con_protocol = PROTOCOL_SPEAKFREE;
  2102.         }
  2103.     }
  2104.  
  2105.     /* If this is a VAT packet, translate it into a sound buffer. */
  2106.  
  2107.     if (((c->con_protocol == PROTOCOL_VAT)) &&
  2108.         (bcmp(((unsigned char *) &sb) + 2, c->con_session, 2) == 0) &&
  2109.         isvat((unsigned char *) &sb, rll)) {
  2110.         if (sb.buffer.buffer_len == 0) {
  2111.         if (Debug) {
  2112.                     fprintf(stderr, "Ignoring unparseable VAT packet.\n");
  2113.         }
  2114.         continue;
  2115.         }
  2116.         wasrtp = TRUE;
  2117.  
  2118.     /* If this is an RTP packet, transmogrify it into a sound
  2119.        buffer we can understand. */
  2120.  
  2121.     } else if ((c->con_protocol == PROTOCOL_RTP) &&
  2122.          (bcmp(((unsigned char *) &sb) + 8, c->con_session, 4) == 0) &&
  2123.          isrtp((unsigned char *) &sb, rll)) {
  2124.         if (sb.buffer.buffer_len == 0) {
  2125.         if (Debug) {
  2126.                     fprintf(stderr, "Ignoring unparseable RTP packet.\n");
  2127.         }
  2128.         continue;
  2129.         }
  2130.         wasrtp = TRUE;
  2131.     }
  2132.  
  2133.     if (!wasrtp) {
  2134.         int xbl;
  2135.  
  2136.         /* Convert relevant fields from network to host
  2137.            byte order, if necessary. */
  2138.  
  2139.         sb.compression = ntohl(sb.compression);
  2140.         sb.buffer.buffer_len = ntohl(sb.buffer.buffer_len);
  2141.  
  2142.         if (sb.compression & fCompRobust) {
  2143.         int aseq = (sb.buffer.buffer_len >> 24) & 0xFF;
  2144.  
  2145.         if (aseq == c->con_rseq) {
  2146.             continue;
  2147.         }
  2148.         c->con_rseq = aseq;
  2149.         sb.buffer.buffer_len &= 0xFFFFFFL;
  2150.         }
  2151.  
  2152.         /* Now if this is a valid Speak Freely packet (as
  2153.            opposed to a VAT packet masquerading as one, or
  2154.                an encrypted VAT or RTP packet we don't have the
  2155.            proper key to decode), the length received from the
  2156.            socket will exactly equal the buffer length plus
  2157.            the size of the header.    This is a reasonably
  2158.            good validity check, well worth it considering the
  2159.            horrors treating undecipherable garbage as a sound
  2160.            buffer could inflict on us. */
  2161.  
  2162.         xbl = sb.buffer.buffer_len + (sizeof(struct soundbuf) - BUFL);
  2163.  
  2164.         /* If this packet is encrypted with an algorithm which requires
  2165.            padding the packet to an 8-byte boundary, adjust the actual
  2166.            content length to account for the padding. */
  2167.  
  2168.         if ((sb.compression & (fEncDES | fEncIDEA | fEncBF | fEncPGP)) != 0) {
  2169.         xbl = ((sb.buffer.buffer_len + 7) & (~7)) +
  2170.               (sizeof(struct soundbuf) - BUFL);
  2171.         }
  2172.  
  2173.             /* If packet is compressed with LPC-10, compensate for "packet
  2174.                stuffing". */
  2175.  
  2176.         if ((sb.compression & fCompLPC10) && (sb.buffer.buffer_len >= 16)) {
  2177.         xbl -= 16;
  2178.         }
  2179.         if (xbl != rll) {
  2180.         if (Debug) {
  2181.             fprintf(stderr,
  2182.                             "Sound buffer length %ld doesn't match %ld byte packet.  Hdr=%08X\n",
  2183.                 xbl, rll, sb.compression);
  2184.         }
  2185.         if (showhosts && c->con_protocol != PROTOCOL_UNKNOWN) {
  2186.                     fprintf(stderr, "%s: %s sending in unknown protocol or encryption.\n",
  2187.                 prog, c->con_hostname);
  2188.         }
  2189.         c->con_protocol = PROTOCOL_UNKNOWN;
  2190.         continue;
  2191.         }
  2192.  
  2193.         /* It does appear to be a genuine Speak Freely sound
  2194.            buffer.    On that basis, set the protocol to Speak Freely
  2195.                even if the buffer isn't explicitly tagged. */
  2196.  
  2197.         if (c->con_protocol != PROTOCOL_SPEAKFREE) {
  2198.         c->con_protocol = PROTOCOL_SPEAKFREE;
  2199.         if (showhosts) {
  2200.                     fprintf(stderr, "%s: %s sending in Speak Freely protocol.\n", prog, c->con_hostname);
  2201.         }
  2202.         c->con_reply_current = FALSE;
  2203.         }
  2204.     }
  2205.  
  2206.  
  2207.     if ((replycmdexe != NULL && !c->con_reply_current)) {
  2208.             char *rcmd = StrReplace(replycmdexe, "%s", c->con_hostname);
  2209.  
  2210.         if (rcmd != NULL) {
  2211.         if (Debug) {
  2212.                     fprintf(stderr, "Executing: %s\n", rcmd);
  2213.         }
  2214.         system(rcmd);
  2215.         c->con_reply_current = TRUE;
  2216.         if (rcmd != replycmdexe) {
  2217.             free(rcmd);
  2218.         }
  2219.         }
  2220.     }
  2221.  
  2222.         /* If this is the first sound packet we've seen from this host
  2223.        in this protocol, create (or update) the reply command file. */
  2224.  
  2225.     if (replyfile != NULL && !c->con_reply_current) {
  2226.  
  2227.         /* If a reply file is requested, create an executable
  2228.            shell script to reply to the host that just connected
  2229.            using either the default command or whatever command
  2230.            the user specifies on the -A option. */
  2231.  
  2232.             FILE *rfp = fopen(replyfile, "w");
  2233.         static char *popt[] = {
  2234.                 "",
  2235.                 "-vat ",
  2236.                 "-rtp ",
  2237.                 "-rtp ",
  2238.                 ""
  2239.         };
  2240.  
  2241.         if (rfp != NULL) {
  2242.                 fprintf(rfp, "#! /bin/sh\n");
  2243.         /* $* allows specifying options on reply file call. */
  2244.                 fprintf(rfp, "%s %s$* %s\n", replycmd,
  2245.                   popt[c->con_protocol], c->con_hostname);
  2246.         /* Make the file executable. */
  2247.         fchmod(fileno(rfp), 0755);
  2248.         fclose(rfp);
  2249.         }
  2250.         c->con_reply_current = TRUE;
  2251.     }
  2252.  
  2253. #ifdef HALF_DUPLEX
  2254.  
  2255.     /* If this is a half duplex mute request, immediately release
  2256.        the audio output device if we have it.  We verify the
  2257.            sender's address and accept mute requests only frome
  2258.        localhost; nobody else has any business telling us
  2259.        to shut up! */
  2260.  
  2261.     if (sb.compression & fHalfDuplex) {
  2262. #ifdef HDX_DEBUG
  2263.         if (Debug) {
  2264.                 static char *hdxreq[4] = { "Bogus(0)", "Mute", "Resume",
  2265.                                            "Bogus(3)" };
  2266.  
  2267.                 fprintf(stderr, "%s: half-duplex %s request from %s.\n",
  2268.             prog, hdxreq[sb.compression & 3], inet_ntoa(from.sin_addr));
  2269.         }
  2270. #endif
  2271.         if (memcmp(&from.sin_addr, &localhost, sizeof localhost) == 0) {
  2272.         if (sb.compression & fHalfDuplexMute) {
  2273.             if (audiok) {
  2274.             soundterm();
  2275.             audiok = FALSE;
  2276.             if (Debug) {
  2277.                             fprintf(stderr, "%s: half-duplex releasing audio output.\n", prog);
  2278.             }
  2279.             }
  2280.             halfDuplexMuted = TRUE;
  2281.         } else if (sb.compression & fHalfDuplexResume) {
  2282.             halfDuplexMuted = FALSE;
  2283.         }
  2284.         }
  2285.         continue;              /* Done with packet */
  2286.     }
  2287. #endif
  2288.  
  2289.     /* If this is a face request and we have a face file open,
  2290.        respond to it.  Note that servicing of face file data requests
  2291.        is stateless. */
  2292.  
  2293.     if (sb.compression & fFaceData) {
  2294.         if (sb.compression & faceRequest) {
  2295.         long l;
  2296.  
  2297.         /* Request for face data. */
  2298.  
  2299.         if (facefile != NULL) {
  2300.             fseek(facefile, sb.buffer.buffer_len, 0);
  2301.             *((long *) sb.buffer.buffer_val) = htonl(sb.buffer.buffer_len);
  2302.             l = fread(sb.buffer.buffer_val + sizeof(long),
  2303.             1, 512 - (sizeof(long) + (sizeof(soundbuf) - BUFL)), facefile);
  2304.             sb.compression = fProtocol | fFaceData | faceReply;
  2305.             if (Debug) {
  2306.                         fprintf(stderr, "%s: sending %d bytes of face data at %ld to %s\n",
  2307.                 prog, l, ntohl(*((long *) sb.buffer.buffer_val)), c->con_hostname);
  2308.             }
  2309.             l += sizeof(long);
  2310.         } else {
  2311.             /* No face file.  Shut down requestor. */
  2312.             sb.compression = fProtocol | fFaceData | faceLess;
  2313.             l = 0;
  2314.         }
  2315.         bcopy((char *) &(from.sin_addr), (char *) &(name.sin_addr),
  2316.             sizeof(struct in_addr));
  2317.  
  2318.         sb.compression = htonl(sb.compression);
  2319.         sb.buffer.buffer_len = htonl(l);
  2320.         if (sendto(sock, (char *) &sb,
  2321.             (int) ((sizeof(struct soundbuf) - BUFL) + l),
  2322.             0, (struct sockaddr *) &(name), sizeof name) < 0) {
  2323.                     perror("sending face image data");
  2324.         }
  2325.         } else if (sb.compression & faceReply) {
  2326.  
  2327.         /* Face data packet received from remote server. */
  2328.  
  2329.         if ((c->face_file == NULL) && (sb.buffer.buffer_len > 0)) {
  2330.                     sprintf(c->face_filename, "%sSF-%s.bmp", FACEDIR, c->con_hostname);
  2331.                     c->face_file = fopen(c->face_filename, "w");
  2332.         }
  2333.         if (c->face_file != NULL) {
  2334.             if (sb.buffer.buffer_len > sizeof(long)) {
  2335.             long lp =  ntohl(*((long *) sb.buffer.buffer_val));
  2336.  
  2337.             if (lp == c->face_address) {
  2338.                 fseek(c->face_file, lp, 0);
  2339.                 fwrite(sb.buffer.buffer_val + sizeof(long),
  2340.                     sb.buffer.buffer_len - sizeof(long), 1,
  2341.                     c->face_file);
  2342.                 if (Debug) {
  2343.                                 fprintf(stderr, "%s: writing %d bytes at %ld in face file %s\n",
  2344.                     prog, sb.buffer.buffer_len - sizeof(long),
  2345.                     lp, c->face_filename);
  2346.                 }
  2347.                 c->face_address += sb.buffer.buffer_len - sizeof(long);
  2348.                 /* Timeout will make next request after the
  2349.                    configured interval. */
  2350.                 c->face_stat = FSreply;
  2351.                 c->face_retry = 0;
  2352.             } else {
  2353.                 if (Debug) {
  2354.                                 fprintf(stderr, "%s: discarded %d bytes for %ld in face file %s, expected data for %ld\n",
  2355.                     prog, sb.buffer.buffer_len - sizeof(long),
  2356.                     lp, c->face_filename, c->face_address);
  2357.                 }
  2358.             }
  2359.             } else {
  2360.             pid_t cpid;
  2361.  
  2362.             if (Debug) {
  2363.                             fprintf(stderr, "%s: closing face file %s\n",
  2364.                 prog, c->face_filename);
  2365.             }
  2366.             fclose(c->face_file);
  2367.             c->face_file = NULL;
  2368.             c->face_stat = FScomplete;
  2369.             faceTransferActive--;
  2370.  
  2371.             /* Start viewer to display face.  We terminate
  2372.                audio output (if active) before doing this since
  2373.                            we don't know the nature of the audio output
  2374.                            resource.  If it's an open file handle which
  2375.                would be inherited by the child process, that
  2376.                would hang the audio device as long as the
  2377.                viewer is active.  */
  2378.  
  2379.             if (audiok) {
  2380.                 soundterm();
  2381.                 audiok = FALSE;
  2382.                 if (Debug) {
  2383.                                 fprintf(stderr, "%s: releasing audio before viewer fork().\n", prog);
  2384.                 }
  2385.             }
  2386.             cpid = fork();
  2387.             if (cpid == 0) {
  2388.                 char geom[30], *gp1 = NULL, *gp2 = NULL;
  2389.  
  2390. #ifdef NEEDED
  2391.                 /* These should be reset by the execlp(). */
  2392.                 signal(SIGHUP, SIG_DFL);
  2393.                 signal(SIGINT, SIG_DFL);
  2394.                 signal(SIGTERM, SIG_DFL);
  2395.                 signal(SIGALRM, SIG_DFL);
  2396.                 signal(SIGCHLD, SIG_DFL);
  2397. #endif
  2398.  
  2399.                 /* Now we need to close any shared resources
  2400.                    that might have been inherited from the parent
  2401.                    process to avoid their being locked up for the
  2402.                                duration of the viewer's execution. */
  2403.  
  2404.                 close(sock);
  2405.                 if (record != NULL) {
  2406.                 fclose(record);
  2407.                 }
  2408.                 if (facefile != NULL) {
  2409.                 fclose(facefile);
  2410.                 }
  2411. #ifdef FACE_SET_GEOMETRY
  2412.                 /* Attempt to reasonably place successive face windows
  2413.                                on the screen to avoid the user's having to place
  2414.                    them individually (for window managers with
  2415.                    interactivePlacement enabled). */
  2416.  
  2417. #define faceInterval 120    /* Interval, in pixels, between successive faces */
  2418.                             sprintf(geom, "-0+%d", facesDisplayed * faceInterval);
  2419.                             gp1 = "-geometry";
  2420.                 gp2 = geom;
  2421. #endif
  2422.                             execlp("xv",  "xv", c->face_filename, gp1, gp2, (char *) 0);
  2423.                             perror("launching face image viewer");
  2424.                 facesDisplayed--;
  2425.                 exit(0);
  2426.                 /* Leave face image around, for the moment, so the user can
  2427.                    try to view it manually. */
  2428.             } else if (cpid == (pid_t) -1) {
  2429.                             perror("creating face image viewer process");
  2430.             } else {
  2431.                 c->face_viewer = cpid;
  2432.                 facesDisplayed++;
  2433.             }
  2434.             }
  2435.         }
  2436.         } else if (sb.compression & faceLess) {
  2437.         if (c->face_file != NULL) {
  2438.             fclose(c->face_file);
  2439.             unlink(c->face_filename);
  2440.         }
  2441.         c->face_stat = FSabandoned;
  2442.         faceTransferActive--;
  2443.         if (Debug) {
  2444.                     fprintf(stderr, "%s: no face image available for %s\n",
  2445.             prog, c->con_hostname);
  2446.         }
  2447.         }
  2448.         continue;              /* Done with packet */
  2449.     }
  2450.  
  2451.     /* If the packet requests loop-back, immediately dispatch it
  2452.        back to the host who sent it to us.    To prevent an infinite
  2453.        loop-back cycle, we clear the loop-back bit in the header
  2454.        before sending the message.    We leave the host of origin
  2455.        unchanged, allowing the sender to identify the packet as
  2456.        one he originated. */
  2457.  
  2458.     if (sb.compression & fLoopBack) {
  2459.         bcopy((char *) &(from.sin_addr), (char *) &(name.sin_addr),
  2460.         sizeof(struct in_addr));
  2461.         sb.compression &= ~fLoopBack;    /* Prevent infinite loopback */
  2462.  
  2463.         sb.compression = htonl(sb.compression);
  2464.         sb.buffer.buffer_len = htonl(sb.buffer.buffer_len);
  2465.         if (sendto(sock, (char *) &sb, rll,
  2466.         0, (struct sockaddr *) &(name), sizeof name) < 0) {
  2467.                 perror("sending datagram message");
  2468.         }
  2469.         sb.compression = ntohl(sb.compression);
  2470.         sb.buffer.buffer_len = ntohl(sb.buffer.buffer_len);
  2471.     }
  2472.  
  2473. #ifdef HALF_DUPLEX
  2474.  
  2475.         /* If we're muted by a transmission in progress on half-duplex
  2476.        audio hardware, this is the end of line for this sound
  2477.        packet. */
  2478.  
  2479.     if (halfDuplexMuted) {
  2480.         if (Debug) {
  2481.                 fprintf(stderr, "%s: %s packet lost by half-duplex muting.\n",
  2482.                 prog, c->con_hostname);
  2483.         }
  2484.         continue;
  2485.     }
  2486. #endif
  2487.  
  2488.         /* If this packet has been "stuffed" for maximum efficiency,
  2489.        un-stuff it at this point. */
  2490.  
  2491.     if ((sb.compression & fCompLPC10) && (sb.buffer.buffer_len >= 16)) {
  2492.         bcopy(sb.sendinghost, (char *) &sb + rll,
  2493.           sizeof sb.sendinghost);
  2494.         rll += sizeof sb.sendinghost;
  2495.     }
  2496.  
  2497.  
  2498. #ifdef CRYPTO
  2499.     if ((sb.compression & fKeyPGP)) {
  2500.         char cmd[256], f[40], kmd[16];
  2501.         FILE *kfile;
  2502.         FILE *pipe;
  2503.         struct MD5Context md5c;
  2504.  
  2505.         MD5Init(&md5c);
  2506.         MD5Update(&md5c, sb.buffer.buffer_val, sb.buffer.buffer_len);
  2507.         MD5Final(kmd, &md5c);
  2508.  
  2509.         if (memcmp(c->keymd5, kmd, 16) != 0) {
  2510.         bcopy(kmd, c->keymd5, 16);
  2511.                 sprintf(f, "/tmp/.SF_SKEY%d", getpid());
  2512.  
  2513.                 kfile = fopen(f, "w");
  2514.         if (kfile == NULL) {
  2515.                     fprintf(stderr, "Cannot open encrypted session key file %s\n", f);
  2516.         } else {
  2517.             fwrite(sb.buffer.buffer_val, sb.buffer.buffer_len, 1, kfile);
  2518.             fclose(kfile);
  2519. #ifdef ZZZ
  2520.             if (pgppass == NULL) {
  2521.             static char s[256];
  2522.  
  2523.                         fprintf(stderr, "Enter PGP pass phrase: ");
  2524.             if (fgets(s, sizeof s, stdin) != NULL) {
  2525.                 s[strlen(s) - 1] = 0;
  2526.                 pgppass = s;
  2527.             }
  2528.             }
  2529. #endif
  2530.                     sprintf(cmd, "pgp -f +nomanual +verbose=0 +armor=off %s%s%s <%s",
  2531.                         pgppass ? "-z\"" : "", pgppass ? pgppass : "",
  2532.                         pgppass ? "\" " : "", f);
  2533. #ifdef PGP_DEBUG
  2534.                     fprintf(stderr, "Decoding session key with: %s\n", cmd);
  2535. #else
  2536.             if (Debug) {
  2537.                        fprintf(stderr, "%s: decoding PGP session key.\n", prog);
  2538.             }
  2539. #endif
  2540.                     pipe = popen(cmd, "r");
  2541.             if (pipe == NULL) {
  2542.                         fprintf(stderr, "Unable to open pipe to: %s\n", cmd);
  2543.             } else {
  2544.             int lr;
  2545.  
  2546.             /* Okay, explanation time again.  On some systems
  2547.                (Silicon Graphics, for example), the timer tick
  2548.                alarm signal can cause the pending read from the
  2549.                            PGP key pipe to return an "Interrupted system
  2550.                            call" status (EINTR) with (as far as I've ever
  2551.                            seen and I sincerely hope it's always) zero bytes
  2552.                read.  This happens frequently when the timer is
  2553.                running and the user takes longer to enter the
  2554.                secret key pass phrase than the timer tick.    So,
  2555.                if this happens we keep on re-issuing the pipe
  2556.                read until the phrase allows PGP to finish the
  2557.                job. */
  2558.  
  2559.             while ((lr = fread(c->pgpkey, 1, 17, pipe)) != 17 &&
  2560.                    (errno == EINTR)) ;
  2561.             if (lr == 17) {
  2562.                 c->pgpkey[0] = TRUE;
  2563. #ifdef PGP_DEBUG
  2564.                 {
  2565.                 int i;
  2566.  
  2567.                                 fprintf(stderr, "Session key for %s:", c->con_hostname);
  2568.                 for (i = 0; i < 16; i++) {
  2569.                                     fprintf(stderr, " %02X", c->pgpkey[i + 1] & 0xFF);
  2570.                 }
  2571.                                 fprintf(stderr, "\n");
  2572.                 }
  2573. #else
  2574.                 if (Debug) {
  2575.                                fprintf(stderr, "%s: PGP session key decoded.\n", prog);
  2576.                 }
  2577. #endif
  2578.             } else {
  2579.                 c->pgpkey[0] = FALSE;
  2580.                             fprintf(stderr, "%s: Error decoding PGP session key.\n", prog);
  2581. #ifdef PGP_DEBUG
  2582.                             fprintf(stderr, "Read status from pipe: %d\n", lr);
  2583.                             perror("reading decoded PGP key from pipe");
  2584. #endif
  2585.             }
  2586.             pclose(pipe);
  2587.             }
  2588.             unlink(f);
  2589.         }
  2590.         }
  2591.     } else
  2592. #endif
  2593.     {
  2594.         playbuffer(&sb, c);
  2595.     }
  2596.     }
  2597. #ifdef MEANS_OF_EXIT
  2598.     close(sock);
  2599. #ifdef CRYPTO
  2600.     desdone();
  2601. #endif
  2602.     gsm_destroy(gsmh);
  2603.     lpc_end();
  2604.     exiting();
  2605.     if (record != NULL) {
  2606.     fclose(record);
  2607.     }
  2608.     if (facefile != NULL) {
  2609.     fclose(facefile);
  2610.     }
  2611.     return 0;
  2612. #endif
  2613. }
  2614.